Tutorial :post data with jQuery and redirect to another action



Question:

View:

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

Controller action:

    [HttpPost]      public ActionResult PostingData(int id, string prezime)      {            //some code            return Json(new { redirect = Url.Action("Create") });      }  

Tnx, this code solve my problem


Solution:1

Instead of returning a redirect, which the AJAX request can't handle, return the URL as JSON and let the post handler change the location.

$.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" ) } );  }  


Solution:2

The reason that the redirect doesn't work is because you are doing an asynchronous request. The response that contains the code for the redirection is just returned as data to the success method, where you ignore it.

Instead, just post the form that you have in the page:

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


Solution:3

controller

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

View

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »