Is it possible to access a Model property in an external Javascript file?
e.g. In "somescript.js" file
var currency = '@Model.Currency';
alert(currency);
On my View
<script src="../../Scripts/somescript.js" type="text/javascript">
This doesn't appear to work, however if I put the javascript directly into the view inside script tags then it does work? This means having to put the code in the page all the time instead of loading the external script file like this:
@model MyModel;
<script lang=, type=>
var currency = '@Model.Currency';
alert(currency);
</script>
Is there any way around this?
I tackled this problem using data attributes, along with jQuery. It makes for very readable code, and without the need of partial views or running static javascript through a ViewEngine. The JavaScript file is entirely static and will be cached normally.
Index.cshtml:
Index.js:
_Layout.cshtml (optional, but good habit):
What i did was create a js object using the Method Invocation pattern, then you can call it from the external js file. As js uses global variables, i encapsulate it to ensure no conflicts from other js libraries. Example: In the view
Now inside of the external page you can then get the data with a protected scope to ensure that it does not conflict with other global variables in js.
Also you can wrap it inside of a Module in the external file to even make it more clash proof. Example:
You could always try RazorJs. It's pretty much solves not being able to use a model in your js files RazorJs
Try JavaScriptModel ( http://jsm.codeplex.com ):
Just add the following code to your controller action:
Now you can access the variable "Currency" in JavaScript.
If this variable should be available on the hole site, put it in a filter. An example how to use JavaScriptModel from a filter can be found in the documentation.
I had the same problem and I did this:
View.
External js.
What you could do is passing the razor tags in as a variable.
In razor File>
in JS file >