views:

57

answers:

2

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? Thanks.

+3  A: 

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.

Steve Michelotti
Good explanation of the problem and a link to a complete solution. Thanks.
John
A: 

The another way is to remove that control/html element through javascript. You can call this script when your Ajax request gets completed.

<%: Ajax.ActionLink(
                "Delete"
                ,"Delete"
                , new { id=item.FooId}
                , new AjaxOptions()
                { 
                    OnSuccess="deleteElement"   
                    ,Confirm="Are you sure that you want to delete this item?"
                    , HttpMethod = "post"} ) %>

OnSuccess Option tells the Ajax helper to call the method when ajax requests gets completed successfully.

ajay_whiz