Razor Syntax in External Javascript

So, as you know, the Razor syntax in ASP.NET MVC does not work in external JavaScript files.

My current solution is to put the Razor syntax in a global variable and set the value of this variable from the mvc view that uses this .js file.

JavaScript file:

function myFunc() { alert(myValue); } 

MVC file view:

 <script language="text/javascript"> myValue = @myValueFromModel; </script> 

I want to know how can I pass myValue directly as a parameter to a function? I prefer to have an explicit call with a parameter than relying on global variables, however I am not very addicted to javascript.

How do I implement this using javascript options? Thanks!

+5
source share
3 answers

Just ask your function to accept the argument and use it in the alert (or anywhere).

external.js

 function myFunc(value) { alert(value); } 

someview.cshtml

 <script> myFunc(@myValueFromModel); </script> 

One thing to keep in mind is that if myValueFromModel is a string, then it will pass as myFunc(hello) , so you need to wrap it in quotation marks so that it becomes myFunc('hello') , like this

 myFunc('@(myValueFromModel)'); 

Note the optional () used with the razor. This helps the engine discern where the gap is between the razor code, so nothing strange happens. This can be useful when there are nested ones ( or " .

change

If this is done several times, then some changes may occur at the end of JavaScript. Mostly, the example shown does not display the script correctly. It will need to be changed. You can use a simple structure like this.

jsFiddle Demo

external.js

 var myFunc= new function(){ var func = this, myFunc = function(){ alert(func.value); }; myFunc.set = function(value){ func.value = value; } return myFunc; }; 

someview.cshtml

 <script> myFunc.set('@(myValueFromModel)'); myFunc();//can be called repeatedly now </script> 
+7
source

I often find that JavaScript in a browser is usually conceptually bound to a specific element. In this case, you may need to associate a value with this element in Razor code, and then use JavaScript to retrieve this value and use it in some way.

For instance:

 <div class="my-class" data-func-arg="@myValueFromModel"></div> 

Static JavaScript:

 $(function() { $('.my-class').click(function() { var arg = $(this).data('func-arg'); myFunc(arg); }); }); 
+3
source

Do you want to immediately execute your function? Or do you want to call a function with a parameter?

You can add a wrapper function with no parameters and inside a call to your function with global var as a parameter. And when you need to call myFunc (), you call it through myFuncWrapper ();

 function myFuncWrapper(){ myFunc(myValue); } function myFunc(myParam){ //function code here; } 
+1
source

All Articles