What is the best way to delete an item in MVC? I have a list of items. Each row will contain a "Delete" link. I want the Delete link to prompt for confirmation, then delete the item from the datastore and refresh the page with the new data.
Here is my view code:
<%: Ajax.ActionLink(
"Delete"
,"Delete"
, new { id=item.FooId}
, new AjaxOptions()
{
Confirm="Are you sure that you want to delete this item?"
, HttpMethod = "post"} ) %>
And here is my controller code:
[HttpPost]
public ActionResult Delete(int id)
{
try
{
var success = FooService.Deletefoo(id);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The record is being deleted, however the page is not refreshing. The only thing that I can think of is that RedirectToAction only works for different pages, not the same page.
How do I get the page to refresh?
CRUD operation in MVC is the basic operations, where CRUD denotes create, read, update, and delete. But before understanding the basic operations of MVC, first, learn about MVC. MVC is the Model View Controller. MVC is a design pattern that is used to differentiate the data from business logic and presentation logic.
You're page is not refreshing because the AJAX call is not going to honor a 302 - the RedirectToAction() is used when the entire browser is refreshing. If you're going to use AJAX for your delete link then have a look at this post for all example code. On complete, it does a javascript window.location.reload(); in order to refresh the page. This follows the PRG pattern.
Another approach is the use to not use AJAX. Here is an example for that.
Overall, you're fine sticking with your AJAX approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With