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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
  • This may help you http://stackoverflow.com/questions/14178430/javascript-dynamic-function-names – NKD Oct 17 '13 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) – pedrommuller Oct 17 '13 at 20:06

6 Answers6

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/)

Remi Beaulieu
  • 127
  • 1
  • 6
5

This was found to work in writing Javascript function names dynamically

@{
    @:function  
        @name<text>_onActivate() {
           ....
        }
   </text>
}
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
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.

Łukasz Stempek
  • 421
  • 6
  • 8
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>
eaglei22
  • 2,589
  • 1
  • 38
  • 53
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.

mayabelle
  • 9,804
  • 9
  • 36
  • 59
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>