Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete item using ASP.Net MVC

Tags:

asp.net-mvc

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?

like image 618
John Avatar asked Sep 14 '10 16:09

John


People also ask

What is CRUD operations in MVC?

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.


1 Answers

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.

like image 62
Steve Michelotti Avatar answered Nov 06 '22 13:11

Steve Michelotti