Reputation: 672
I have _LayoutOnecs.html file and View Loads with in it renderbody and displays list of records in table. in one of table column i have a Delete icon on click of it goes to controller and deletes record from database once the record is deleted the view should be refreshed so i returned the action to controller which fetches all the records
public ActionResult GetAdvertisementDetails()
{
var advertisementList = new AdvertisementManager().GetAdvertisementDetails();
return View("AdvertisementDetails", advertisementList);
}
public ActionResult DeleteAdvertisementDetails(int id)
{
new AdvertisementManager().DeleteAdvertisementDetails(id);
return RedirectToAction("GetAdvertisementDetails", "Advertisement");
}
once Delete is done it is going to GetAdvertisementcontroller and return view but the Deleted record sits there in table if i Refresh the page by pressing F5 the record is removed from table. How do i Refresh automatically when the record is deleted
View Code
<div class="col-md-12 main_table">
<div class="table-responsive">
<table class="table" id="hom_table">
<tr>
<th>Advertisement Name</th>
<th>Link</th>
<th>Start Date</th>
<th>End Date</th>
<th width="100">Action</th>
</tr>
@foreach (var advertisements in Model)
{
<tr>
<td> @advertisements.Description</td>
<td> @advertisements.ImageUrl</td>
<td> @advertisements.StartDate</td>
<td> @advertisements.EndDate</td>
<td>
<a onclick="EditadvertisementDetails(@advertisements.AdvertisementId)">
<i class=" pull_Advt_details tbl_edit_btn fa fa-edit Editbutton"></i>
</a>
<a id="Deladvertisement" onclick="Deleteadvertisement(@advertisements.AdvertisementId)" >
<i class="tbl_del_btn fa fa-trash"></i>
</a>
</td>
</tr>
}
</table>
</div>
<!-- Responsive main table Ends -->
</div>
Upvotes: 2
Views: 23176
Reputation:
Ajax calls stay on the same page. Your use of return RedirectToAction("GetAdvertisementDetails", "Advertisement");
in the controller method is ignored. Its also unnecessary to redirect since you can just remove the row from the table
Modify the html to (note remove the id
attribute which is generating invalid html):
<a class="delete" data-id="@advertisements.AdvertisementId>
<i class="tbl_del_btn fa fa-trash"></i>
</a>
and use the following script to call the controller method and remove the row
var url = '@Url.Action("DeleteAdvertisementDetails", "Advertisement")';
$('.delete').click(function() {
var row = $(this).closest('tr');
$.post(url, { id: $(this).data('id') }, function(response) {
if(response) {
row.remove();
}
}).fail(function (response) {
// display error message?
});
});
and modify the controller to
[HttpPost]
public JsonResult DeleteAdvertisementDetails(int id)
{
new AdvertisementManager().DeleteAdvertisementDetails(id);
return Json(true);
}
Upvotes: 2