Donate

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.

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations