在 javascript 代码中使用 Url.Action 的更好解决方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4781552/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better solution to using Url.Action in javascript code
提问by Simon
In my current project using asp.net MVC 3 (using razor), when I'm making Ajax calls, I have to keep the JS on the view page because I want to use Url.Action to generate the URL. This means I can't split the js code out into .JS files, Is there a better solution than what I'm currently doing.
在我当前使用 asp.net MVC 3(使用 razor)的项目中,当我进行 Ajax 调用时,我必须将 JS 保留在视图页面上,因为我想使用 Url.Action 来生成 URL。这意味着我无法将 js 代码拆分为 .JS 文件,是否有比我目前正在做的更好的解决方案。
采纳答案by Jamiec
I tend to accomplish this in a similar way as above, with a slightly different twist as I like namespacing my javascript.
我倾向于以与上述类似的方式完成此操作,但略有不同,因为我喜欢命名我的 javascript。
The javascript file looks something like:
javascript 文件类似于:
var my = {};
my.viewname = 
{
   init : function(settings){
      // do some work here. settings.someImportantUrl has my json/ajax url eg.
      alert(settings.someImportantUrl );
   }
}
Then my view would contain something like:
然后我的观点将包含如下内容:
<script language='javascript'>
  // allocate an object with variables you want to use in the external js file
  var settings = {someImportantUrl: '<%=Url.Action(...)%>'};
  // call an init method for the current view
  my.viewname.init(settings);
</script>
回答by Egor4eg
You can define only urls in view and keep all other javascript code in .js files.
您只能在视图中定义 url,而将所有其他 javascript 代码保留在 .js 文件中。
There is code from view in my MVC.NET 1 application:
在我的 MVC.NET 1 应用程序中有来自视图的代码:
<script type="text/javascript" src="<%=Url.Content("~/Scripts/Account/ManageUsers.js")%>"></script>
<script type="text/javascript" src="<%=Url.Content("~/Scripts/Account/ManageUsersAndGroups.js")%>"></script>
<script type="text/javascript">
    var getUsersUrl = '<%= Url.Action("GetUsers", "Account") %>';
    var getUserDetailsURL = '<%= Url.Action("GetUserDetails", "Account") %>';
    <%If Not ViewData("readOnly") Then%>
    var changeRolePermissionsUrl = '<%= Url.Action("ChangeRolePermissions", "Account") %>';
    var deleteUserUrl = '<%= Url.Action("DeleteUser", "Account") %>';
    var resetPasswordUrl = '<%= Url.Action("ResetPassword", "Account") %>';
    var updateUserGroupsUrl = '<%= Url.Action("UpdateUserGroups", "Account") %>';
    var updateUserDetailsUrl = '<%= Url.Action("UpdateUserDetails", "Account") %>';
    <%End If%>  
</script>
So, you can even don't render urls for actions which cannot be invoked by user because of security reasons. (ViewData("readOnly")means user have read only access to screen).
因此,由于安全原因,您甚至可以不为用户无法调用的操作呈现 url。(ViewData("readOnly")意味着用户对屏幕具有只读访问权限)。
And there is a part of code in js file:
并且在js文件中有一部分代码:
function GetUsersList() {
    ajax.getJSON(getUsersUrl, {}, function(data) {
        if (data != false) {
            ShowUsers(data);
        }
        else {
            jAlert('Error during users list retrieving.');
        }
    });
}
Where getUsersUrlis defined in View
凡getUsersUrl在视图中定义
回答by Adeel
your javascript code should be reside in separate javascript file. you can use global variables to link your view and javascript. E.g. view page looks like below.
您的 javascript 代码应该驻留在单独的 javascript 文件中。您可以使用全局变量来链接您的视图和 javascript。例如查看页面如下所示。
view html ...
<script type="text/javascript">
var pageUrl = @GetURL()
</script>
<script type="text/javascript" src="/js/script.js"/>
script.jsfile use the pageUrlvariable and other global variables.
script.js文件使用pageUrl变量和其他全局变量。
回答by scott-pascoe
I'm not sure of security ramifications on this, but another way to do it would be to use the @Url.Action to set the 'id' of the html markup, then you can create a javascript click function, like the following:
我不确定这对安全性的影响,但另一种方法是使用 @Url.Action 设置 html 标记的“id”,然后您可以创建一个 javascript 单击函数,如下所示:
View
看法
<div class="someClickable" id='@Url.Action("Action", "Controller")'>
</div>
Referenced javascript file
引用的javascript文件
$(function() {
    $('someClickable').click(function () {
        $.ajax({
            url: this.id,
            success: someJSFunction,
            dataType: "html"
        });
    });
});
You end up with the desired url stored in the 'id' of the 'div'. This seems to be a reasonable solution as long as you are doing read only actions.
您最终将所需的 url 存储在“div”的“id”中。只要您执行只读操作,这似乎是一个合理的解决方案。

