Sunday, March 12, 2017

View in ASP.NET MVC not refreshing after calling Ajax Post in jQuery UI

Hello,
In an application wherein the controller is invoked using Ajax POST and that controller will redirect to a landing page such as Index after processing, an issue will occur such as the View of that landing page isn't updated or not refreshed. Normally, the View will be updated since the model is queried from the database.
[HttpPost]
public ActionResult Delete(int id)
{
 try
 {
  Customer customer = _customer.Customers.FirstOrDefault(t => t.CustomerID == id);
  if (customer != null)
  {
   _customer.Customers.Remove(customer);
   _customer.SaveChanges();
  }
 }
 catch
 {
  //TODO
 }

 return RedirectToAction("Index");
}
The fix for that is to change the RedirectToAction() statement to return the url of a landing page as JSON result. And in the ajax statement, add a statement that navigate to the url returned from the controller.
[HttpPost]
public ActionResult Delete(int id)
{
 try
 {
  Customer customer = _customer.Customers.FirstOrDefault(t => t.CustomerID == id);
  if (customer != null)
  {
   _customer.Customers.Remove(customer);
   _customer.SaveChanges();
  }
 }
 catch
 {
  //TODO
 }

 var url = this.Url.Action("Index", "Customer", null, Request.Url.Scheme);
 return Json(new { Url = url });
}
JavaScript Code:
$.post(url,"", function (data) {
 alert('Record successfully deleted from database!');
 window.location.href = data.Url
});
See related issue here: Return View() statement not redirecting to View in ASP.NET MVC using $.ajax() post.

0 comments:

Post a Comment