ASP.NET MVC 3 Razor:如何在 Javascript 字符串变量中获取操作 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6092964/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:11:56  来源:igfitidea点击:

ASP.NET MVC 3 Razor: How to get Action URL in a Javascript string variable?

javascriptasp.net-mvc-3razor

提问by Zachary Scott

@(Html.ActionLink("Link Label", 
    "ActionMethodName", 
    "ControllerName", 
    null, // parameter object, then html object
    null))

produces

产生

<a href="/ControllerName/ActionMethodName/">Link Label</a>

If I want to reference the /ControllerName/ActionMethodName/idin a JavaScript template for the Editor Newlink, how would I assign that to a JavaScript variable?

如果我想/ControllerName/ActionMethodName/id在 JavaScript 模板中引用EditNew链接,我将如何将其分配给 JavaScript 变量?

attempt:

试图:

<script type="text/javascript">
    var actionUrl = '@(Html.ActionLink("","ActionMethodName",
                                       "ControllerName",null,null))';
</script>

but at that point, I would have to use Javascript to remove the unwanted <a href...characters in the string.

但那时,我将不得不使用 Javascript 来删除<a href...字符串中不需要的字符。

回答by Justin Soliz

@Url.Action("ActionMethodName", "ControllerName")will generate a path.

@Url.Action("ActionMethodName", "ControllerName")将生成一条路径。

回答by Darin Dimitrov

<script type="text/javascript">
    var actionUrl = @Html.Raw(Json.Encode(Url.Action("ActionMethodName", "ControllerName")));
</script>

or if you already have this actionLink somewhere inside the page you could use it directly:

或者,如果您已经在页面内的某处拥有此 actionLink,则可以直接使用它:

var actionUrl = $('#mylink').attr('href');

Just ensure to provide a unique id in order to simplify the selection:

只需确保提供唯一 id 以简化选择:

@(Html.ActionLink(
    "Link Label", 
    "ActionMethodName", 
    "ControllerName", 
    null,
    new { id = "mylink" })
)