asp.net-mvc 为 url.action 发布操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2230722/
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
post action for url.action?
提问by Rod
Here is a line of code in my Controller class:
这是我的 Controller 类中的一行代码:
return JavaScript(String.Format("window.top.location.href='{0}';", Url.Action("MyAction", "MyController")))
Is there a way to make it use the verb=postversion of MyAction?
有没有办法让它使用 的verb=post版本MyAction?
回答by Oundless
I came across the same problem myself and solved it using a data-attribute and some jQuery. The benefit of doing it this way is that you still get the correct URL when you hover over the link, even though it does a POST. Note that the Html.BeginFormcontains the default action in case the user hits the enter key.
我自己遇到了同样的问题,并使用一个data-属性和一些 jQuery解决了它。这样做的好处是,当您将鼠标悬停在链接上时,您仍然可以获得正确的 URL,即使它执行了 POST。请注意,Html.BeginForm包含默认操作,以防用户按回车键。
HTML(ASP.NET MVC3 Razor)
HTML(ASP.NET MVC3 Razor)
@using (Html.BeginForm("Quick", "Search"))
{
<input type="text" name="SearchText" />
<a href="@Url.Action("Quick", "Search")" data-form-method="post">Search</a>
<a href="@Url.Action("Advanced", "Search")" data-form-method="post">Advanced</a>
}
jQuery
jQuery
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $(this);
form.attr("action", action);
form.submit();
});
});
回答by Matt Lacey
You can't use POST by simply navigating to a different URL. (Which is what you'd do by changing location.href.)
您不能通过简单地导航到不同的 URL 来使用 POST。(这是您通过更改 location.href 所做的。)
Using POST only makes sense when submitting some data. It's not clear from your code what data would actually be POSTed.
仅在提交某些数据时使用 POST 才有意义。从您的代码中不清楚实际会发布哪些数据。
If you really want to initiate a POST via javascript try using it to submit a form.
如果您真的想通过 javascript 启动 POST,请尝试使用它来提交表单。
回答by Seth Petry-Johnson
Continuing off of Matt Lacey's answer, your action could return a bit of Javascript that does this:
继续 Matt Lacey 的回答,您的操作可能会返回一些执行此操作的 Javascript:
- Use jquery to add a new form to the DOM
- Use jquery to submit the newly added form
- 使用 jquery 向 DOM 添加新表单
- 使用jquery提交新添加的表单
Something like this: (untested code)
像这样:(未经测试的代码)
var urlHelper = new UrlHelper(...);
var redirectUrl = urlHelper.Action("MyAction", "MyController");
var redirectScript = String.Format(@"
var formTag = $('<form action=""{0}"" method=""post"" id=""redirectForm""></form>');
$(body).append(formTag);
formTag.submit();"
, redirectUrl
);
return JavaScript(redirectScript);

