4

I am trying to create the name of a function dynamically:

I set the name in razor code:

 @ { name="bob"; }

Then I try to create the javascript function, but the syntax is wrong.

function @name@:_onActivate() {
   .....
}

How can I use @name in the name of the function?

2
  • This may help you stackoverflow.com/questions/14178430/… Commented Oct 17, 2013 at 16:29
  • what about to use a html helper that output the javascript function as a mvsString based on your model, something like @Html.DynamicJavascript(Model) Commented Oct 17, 2013 at 20:06

6 Answers 6

8

I know im late to the party, but i had the same question and came up with this..

Use the @() Razor syntax:

function @(Model.Name)_Init() { .....some code... }

Works like a charm

(http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/)

Sign up to request clarification or add additional context in comments.

Comments

5

This was found to work in writing Javascript function names dynamically

@{
    @:function  
        @name<text>_onActivate() {
           ....
        }
   </text>
}

Comments

1

There is also another option:

@{
     var functionStart = "function " + name + "_onActivate()";
}

@functionStart
{
    ...
}

This method doesn't make so much mess in Visual Studio in some cases.

Comments

1

This worked well for me:

@{
    var someFuncName          = "someFuncName";
    var someFuncName2         = "someFuncName" + Model.type;
    var someDynamicFunc       =  Model.funcName;
    var someFuncNameComplete  =  "functionHelper()";
}

<script type="text/javascript">
    function @someFuncName@{<text>()</text>}{
        ...
    }
    function @someFuncName2@{<text>(data)</text>}{
        ...
    }
    function @someDynamicFunc@{<text>()</text>}{
        ...
    }
    function @someFuncNameComplete{
        ...
    }
</script>

Comments

0

If your JavaScript is in the view (rather than its own js file - though I'm not saying I think this is advisable), you can try wrapping your JS code in <text> tags, so that the parser switches back to HTML mode (vs C# mode).

Another alternative may be not naming the function dynamically but instead passing in the name as a parameter - but whether that would work may depend on your design/implementation.

Comments

0

First you can set the function name in a string with below structure:

@{ 
    string name = "bob";
    string funcTxt = name + "_onActivate()"; 
}

Then you can use this string into your function declaration:

<script>
function @funcTxt {
    ...
}
</script>

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.