Access a Model property in a javascript file?

2020-02-10 12:59发布

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?

7条回答
家丑人穷心不美
2楼-- · 2020-02-10 13:42

There is no way to implement MVC / Razor code in JS files.

You should set variable data in your HTML (in the .cshtml files), and this is conceptually OK and does not violate separation of concerns (Server-generated HTML vs. client script code) because if you think about it, these variable values are a server concern.

Take a look at this (partial but nice) workaround: Using Inline C# inside Javascript File in MVC Framework

查看更多
登录 后发表回答