摆脱硬codeD字符串在JavaScript中的ASP.NET MVC [英] Getting rid of hardcoded strings in JavaScript with ASP.NET MVC

查看:129
本文介绍了摆脱硬codeD字符串在JavaScript中的ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个项目,我的工作,我们有很多的JavaScript文件,我们已经很难codeD URL到控制器动作的几个问题。

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. 硬codeD网址proned到错误键入

  2. 在JavaScript脚本的硬codeD的URL,如果相关的控制器或动作的名称已更改将导致破损

  3. 像ReSharper的(据我所知)工具不能静态分析它的方式来称不使用动作,如果指向它的网址是硬codeD。

问题(S)

我们如何才能避免在JavaScript中使用硬codeD网址吗? - 是否有任何现有的框架存在,可以解决这个问题。

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

敬候您的见解。

感谢。

推荐答案

在你的情况,你需要通过URL来JS code文件从意见与使用URL帮手。
修改您的JS文件使用模块模式之一。

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));

查看

<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));

查看

<script type="text/javascript" src="jsfile.js" /> 
<script type="text/javascript">
    module('@Url.Action("action", "controller")');
</script>

这篇关于摆脱硬codeD字符串在JavaScript中的ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆