0

I have a function in asp.net mvc , in razor template . I want to naming my function dynamically . but how can I do this ? this is my function :

function ipro-@count() {
                numpro-@count = numpro-@count + 1;
                document.getElementById("numpro-@count").innerHTML = numpro-@count;
            }

count is a dynamic number . it does not work for function name . how can I fix it ?

6
  • You can't have a - in a function name. What string do you actually want to output as the function name, i.e., how would you like the code to look in the browser if you say View Page Source? Judging by what that function seems to be trying to do I think you're trying to solve the underlying problem the wrong way. Why don't you change the function to accept the number as an argument: function ipro(num) { document.getElementById("numpro" + num)... Commented Sep 19, 2012 at 7:19
  • When I clean - , it shows me numpro@count as a function name . but @count shoud return a number . for example numpro1 or numpro2 . Commented Sep 19, 2012 at 7:22
  • @tsukimi Please show me tsukimi . I'm not professional in jquery . Commented Sep 19, 2012 at 7:26
  • I used function ipro(num) , but it does not work .. Commented Sep 19, 2012 at 7:27
  • Its not jquery ,its razor, ill put answer below Commented Sep 19, 2012 at 7:28

2 Answers 2

4

What happens if you do this, need to add the parens around the variable name

             function ipro@(count) () {
                numpro@(count) = numpro@(count) + 1;
                document.getElementById("numpro@(count)").innerHTML = numpro@(count);
            }
Sign up to request clarification or add additional context in comments.

3 Comments

It shows error because of function naming . function name can't accept - symbol .
It shows error again . in this solution it returns ipro@count as function name not ipro1 for example .
Updated the answer , tested it
0

You could use simple workaround for this concrete situation (when javascript is not too large and complex)

@{
    int count = 3;
}
@helper outputFunction(int count)
{
    @Html.Raw(string.Format("function ipro{0}() {{ numpro-{0} = numpro-{0} + 1; document.getElementById('numpro-{0}').innerHTML = numpro-{0}; }}", count));
}

<!DOCTYPE html>
<html>
<head>

    <title>@ViewBag.Title</title>
</head>
<body>
    <script>
        @outputFunction(count);
    </script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.