在 JavaScript 中为 ASP.NET MVC 生成操作 URL

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

Generating an action URL in JavaScript for ASP.NET MVC

asp.netjavascriptasp.net-mvc

提问by canxss

I'm trying to redirect to another page by calling an action in controller with a specific parameter. I'm trying to use this line:

我正在尝试通过使用特定参数调用控制器中的操作来重定向到另一个页面。我正在尝试使用这一行:

window.open('<%= Url.Action("Report", "Survey",
    new { id = ' + selectedRow + ' } ) %>');

But I couldn't make it work; it gives the following error:

但我无法让它发挥作用;它给出了以下错误:

CS1012: Too many characters in character literal.

CS1012: Too many characters in character literal.

Can't I generate the action URL this was on the client side? Or do I have to make an Ajax call by supplying the parameter and get back the needed URL? This doesn't seem right, but I want to if it's the only way.

我不能在客户端生成操作 URL 吗?或者我是否必须通过提供参数来进行 Ajax 调用并取回所需的 URL?这似乎不对,但如果这是唯一的方法,我想这样做。

Is there an easier solution?

有更简单的解决方案吗?

回答by Dylan Beattie

Remember that everything between <% and %> is interpreted as C# code, so what you're actually doing is trying to evaluate the following line of C#:

请记住,<% 和 %> 之间的所有内容都被解释为 C# 代码,因此您实际上正在尝试评估以下 C# 行:

Url.Action("Report", "Survey", new { id = ' + selectedRow + ' } )

C# thinks the single-quotes are surrounding a character literal, hence the error message you're getting (character literals can only contain a single character in C#)

C# 认为单引号是围绕字符文字,因此您得到的错误消息(字符文字只能包含 C# 中的单个字符)

Perhaps you could generate the URL once in your page script - somewhere in your page HEAD, do this:

也许您可以在页面脚本中生成一次 URL - 在页面 HEAD 中的某处,执行以下操作:

var actionUrl =
    '<%= Url.Action("Report", "Survey", new { id = "PLACEHOLDER" } ) %>';

That'll give you a Javascript string containing the URL you need, but with PLACEHOLDER instead of the number. Then set up your click handlers as:

这会给你一个包含你需要的 URL 的 Javascript 字符串,但是用 PLACEHOLDER 而不是数字。然后将您的点击处理程序设置为:

window.open(actionUrl.replace('PLACEHOLDER', selectedRow));

i.e. when the handler runs, you find the PLACEHOLDER value in your pre-calculated URL, and replace it with the selected row.

即当处理程序运行时,您会在预先计算的 URL 中找到 PLACEHOLDER 值,并将其替换为所选行。

回答by Jaco Pretorius

I usually declare a javascript variable in the section to hold the root of my website.

我通常在该部分声明一个 javascript 变量来保存我的网站的根目录。

<%="<script type=\"text/javascript\">var rootPath = '"
    + Url.Content("~/") + "';</script>" %>

To solve your problem I would simply do

为了解决你的问题,我会简单地做

window.open(rootPath + "report/survey/" + selectedRow);

回答by Israfel

Could you do

你能做吗

window.open('/report/survey/' + selectedRow);

instead where selected row I assume is the id? The routing should pick this up fine.

相反,我假设的选定行是 ID?路由应该可以很好地解决这个问题。

or use getJSON

或使用 getJSON

Perhaps you could use JSONResult instead. Wherever the window.open should be call a method instead i.e. OpenSurveyWindow(id);

也许您可以改用 JSONResult。无论在哪里 window.open 应该调用一个方法,即 OpenSurveyWindow(id);

then add some jquery similar to below

然后添加一些类似于下面的jquery

function OpenSurveyWindow(id){
      $.getJSON("/report/survey/" + id, null, function(data) {
          window.open(data);
     });
}

now in your controller

现在在你的控制器中

public JsonResult Survey(int id)
{
    return Json(GetMyUrlMethod(id));
}

That code isnt syntactically perfect but something along those lines should work

该代码在语法上并不完美,但应该可以使用这些代码

回答by Premson Baby

Just if someone is still looking for this. The controller action can have normal parameters or a model object with these fields. MVC will bind the valus automatically.

只是如果有人还在寻找这个。控制器操作可以具有普通参数或具有这些字段的模型对象。MVC 会自动绑定这些值。

 var url = '@Url.Action("Action", "Controller")';
 $.post(url, {
      YearId: $("#YearId").val(),
      LeaveTypeId:  $("#LeaveTypeId").val()
 }, function (data) {
      //Do what u like with result
 });

回答by Pharabus

You wont be able to do this, the URL.Action is a server side process so will parse before the clientside selectedRow is available. Israfel has the answer I would suggest.

您将无法执行此操作,URL.Action 是服务器端进程,因此将在客户端 selectedRow 可用之前进行解析。Israfel 有我建议的答案。

回答by Brian Mains

If selectedRow is a client-side variable, it won't work. You have to use @Israfel implementation to link. This is because the server-side runs before the client-side variable even exists.

如果 selectedRow 是客户端变量,它将不起作用。您必须使用 @Israfel 实现来链接。这是因为服务器端在客户端变量甚至存在之前运行。

If selectedRow is a server-side variable within the view, change to this:

如果 selectedRow 是视图中的服务器端变量,请更改为:

window.open('<%= Url.Action("Report", "Survey", new { id = selectedRow } ) %>');

window.open('<%= Url.Action("Report", "Survey", new { id = selectedRow } ) %>');

This is because the id will infer the selectedRow variable type, or you could convert to string with ToString() method (as long as it's not null).

这是因为 id 将推断 selectedRow 变量类型,或者您可以使用 ToString() 方法转换为字符串(只要它不为空)。

回答by Kenny Evitt

A way to do this that might be considered cleaner involves using the T4MVC T4 templates. You could then write the JavaScript inside your view like this:

一种可能被认为更简洁的方法是使用T4MVC T4 模板。然后,您可以在视图中编写 JavaScript,如下所示:

var reportUrl = '<%= Url.JavaScriptReplacableUrl(MVC.Survey.Report())%>';
reportUrl = myUrl.replace('{' + MVC.Survey.ReportParams.id + '}', selectedRow);

window.open(reportUrl);

The advantage of this is that you get compile-time checking for the controller, action, and action parameter.

这样做的好处是您可以在编译时检查控制器、动作和动作参数。

回答by user2792022

One more thing that can be done, no so clean i guess:

还有一件事可以做,我猜没有那么干净:

var url = "@Url.RouteUrl(new { area = string.Empty, controller = "Survey", action = "Report" })";
var fullUrl = url  + '?id=' + selectedRow;

回答by maxspan

The easiest way is to declare a javascript variable than concate your parameter value to the link.

最简单的方法是声明一个 javascript 变量,而不是将参数值连接到链接。

  var url = '@Url.Action("Action","Controller")' + "/" + yourjavascriptvariable;
  <a href='" + url + "'>