开发者

How do I delete item using 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 del开发者_StackOverflow社区ete 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜