简体   繁体   中英

How to update view after deleting record in asp.net mvc

I have a view inside which i am saving records to the database and showing that records with Viewbag variable on same page i have a delete button in front of each record to delete records, i want after deleting the record the view should get updated how to achieve that

My controller method

   public ActionResult Delete(int id)
    {
        db.Delete<Logs>(id);
        return RedirectToAction("Index", new { id });
    }

My html and query

<button type="button" id="delete" data-id="@item.LogId" class="delete btn btn-default" style="background-color:transparent"><i class="fas fa-times h3" style="color:red;"></i></button>

        $('.delete').click(function () {
            var selectedid = $(this).data("id");
            $.post("@Url.Action("Delete", "Log")", { id: selectedid });

        });

First thing you should know is RedirectToAction won't work in AJAX call, you should pass URL to redirect with location.href as follows:

Controller Action

[HttpPost]
public ActionResult Delete(int id)
{
    db.Delete<Logs>(id);

    // other stuff

    string url = this.Url.Action("Index", "Log", new { id = id });

    return Json(url);
}

jQuery

$.post("@Url.Action("Delete", "Log")", { id: selectedid }, function (result) {
    window.location.href = result;
});

Or better to create a partial view that contains all elements to be updated via AJAX and pass it into success part afterwards:

Controller Action

[HttpPost]
public ActionResult Delete(int id)
{
    db.Delete<Logs>(id);

    // other stuff

    return PartialView("PartialViewName");
}

jQuery

$.post("@Url.Action("Delete", "Log")", { id: selectedid }, function (result) {
    $('#targetElement').html(result);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM