简体   繁体   English

为url.action发布操作?

[英]post action for url.action?

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=post version of MyAction ? 有没有办法使它使用MyActionverb=post版本?

I came across the same problem myself and solved it using a data- attribute and some jQuery. 我本人也遇到了同样的问题,并使用data- Attribute和一些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. 这样做的好处是,即使将鼠标悬停在链接上,您仍然会获得正确的URL,即使它执行了POST。 Note that the Html.BeginForm contains the default action in case the user hits the enter key. 请注意,如果用户点击Enter键,则Html.BeginForm包含默认操作。

HTML (ASP.NET MVC3 Razor) HTML (ASP.NET MVC3剃刀)

@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();
    });
});

You can't use POST by simply navigating to a different URL. 您不能仅通过导航到其他URL来使用POST。 (Which is what you'd do by changing location.href.) (这是通过更改location.href来完成的。)

Using POST only makes sense when submitting some data. 仅在提交某些数据时使用POST才有意义。 It's not clear from your code what data would actually be POSTed. 从您的代码尚不清楚实际将要发布哪些数据。

If you really want to initiate a POST via javascript try using it to submit a form. 如果您真的想通过javascript启动POST,请尝试使用它提交表单。

Continuing off of Matt Lacey's answer, your action could return a bit of Javascript that does this: 继续根据Matt Lacey的回答,您的操作可能会返回一些执行此操作的Javascript:

  1. Use jquery to add a new form to the DOM 使用jquery向DOM添加新表单
  2. Use jquery to submit the newly added form 使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM