2010-06-29 47 views
2

查看:后数据重定向到另一个动作

<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,这段代码解决我的问题

+0

你需要使用JavaScript来发表您的形式,任何理由? – 2010-06-29 12:07:35

+0

看看[这个问题](http://stackoverflow.com/questions/2903685/jquery-preventing-redirecttoaction-from-working)。 – silent 2010-06-29 12:00:44

回答

10

而不是返回一个重定向,其中, AJAX请求无法处理,将URL作为JSON返回并让帖子处理程序更改位置。

$.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

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

相反,只是张贴您在页面的格式如下:

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

控制器

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