2

We have a few problems in a project I am working on, where we have a lot of JavaScript files, where we have hardcoded URLs to controller actions.

  1. Hardcoded URLs are proned to mistyping
  2. Hardcoded URLs in JavaScript scripts will cause a breakage if the related controller or action's name is changed
  3. Tools like ReSharper (to my knowledge) can't statically analyse it's way to saying the an action is not used, if the URLs pointing to it are hardcoded.

Question(s)

How can we avoid using hardcoded URLs in JavaScript ? - are there any existing frameworks out there that could solve this problem ?

Look forward to hearing your insight.

Thanks.

4

1 回答 1

1

在您的情况下,您需要使用 url 助手将 url 从视图传递给 js 代码文件。修改您的 js 文件以使用模块模式之一。

第一种方式 - 全局变量的导入:

js

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

看法

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

第二种方式 - 导出模块:

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

看法

<script type="text/javascript" src="jsfile.js" /> 
<script type="text/javascript">
    module('@Url.Action("action", "controller")');
</script>
于 2013-07-01T02:58:07.413 回答