Reputation: 53
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 });
});
Upvotes: 1
Views: 1886
Reputation: 24957
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);
});
Upvotes: 2