Getting rid of hardcoded strings in JavaScript with ASP.NET MVC

寵の児 提交于 2019-12-01 11:01:34

In your case you need to pass urls to js code files from views with using url helpers. Modify your js files to use one of module pattern.

First way - importing of global variables:

js

(function (url) {
    // your code 
}(external_url));

view

<script type="text/javascript">
    var external_url = '@Url.Action("action", "controller")'; // define global variable `external_url` with helper. This should be defined before script run.
</script>
<script type="text/javascript" src="jsfile.js" /> 

Second way - exporting module:

var module = (function (url) {
    // your code 
}(external_url));

view

<script type="text/javascript" src="jsfile.js" /> 
<script type="text/javascript">
    module('@Url.Action("action", "controller")');
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!