【问题标题】:post data with jQuery and redirect to another action使用 jQuery 发布数据并重定向到另一个操作
【发布时间】:2010-06-29 11:56:54
【问题描述】:

查看:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Index</h2>

<script type="text/javascript">


$(document).ready(function() {

   $(document).ready(function() {

    $("#example").submit(function() {
        var id = $("#id").val();
        var prezime = $("#prezime").val();

        $.post("/jQueryPost/PostingData", { id: id, prezime: prezime }, function(res) {
            if (res.redirect) {
                window.location.href = res.redirect;
                return;
            }

        }, "json");
        return false;
    });
});
</script>

<form id="example" method = "post">

    Id:<input id="id" type="text" />
    Prezime:<input id="prezime" type="text" />

<p>
    <input type="submit" value="Post Data" />
</p>
</form>

</asp:Content>

控制器动作:

    [HttpPost]
    public ActionResult PostingData(int id, string prezime)
    {

        //some code

        return Json(new { redirect = Url.Action("Create") });
    }

Tnx,这段代码解决了我的问题

【问题讨论】:

  • 有什么理由需要使用 javascript 来发布表单?

标签: asp.net-mvc


【解决方案1】:

不要返回 AJAX 请求无法处理的重定向,而是将 URL 作为 JSON 返回并让 post 处理程序更改位置。

$.post("/jQueryPost/PostingData", { id: id, prezime: prezime }, function(data) {
    location = data.url;
});

[HttpPost]
public ActionResult PostingData(int id, string prezime)
{

    //some code

    return Json( new { url = Url.Action( "Create" ) } );
}

【讨论】:

    【解决方案2】:

    重定向不起作用的原因是您正在执行异步请求。包含重定向代码的响应只是作为数据返回到success方法,您忽略它。

    相反,只需发布​​您在页面中的表单:

    $('#example').attr('action', '/jQueryPost/PostingData/').submit();
    

    【讨论】:

      【解决方案3】:

      控制器

      public ActionResult DeleteMenuItem(int id)
      {
          _menuService.DeleteMenuItemById(id);
          return Json(new { url = Url.Action("Index","Menu") }, JsonRequestBehavior.AllowGet);
      }
      

      查看

      $.getJSON( "/Menu/DeleteMenuItem", { id: parseInt(id)}, function(data) {
          location = data.url;
      } );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多