On my MVC3 razor page, I am using a webgrid to show a list of approx 100 plus records.
I am setting a page size to 10 and paging and sorting is working fine. My only issue here is on my page I have a "delete" hyperlink on the webgrid. When I click "delete", it will delete the record and reload the page. But when reloading the page it goes back to the page1
For instance, if I am on page4 and I click "delete", it deletes that record and comes to the page1, but I want to remain in page4 itself. Any suggestions on how to achieve this.
public ViewResult Index(int? page, string sort)
{
var startPage = 0;
if (page.HasValue && page.Value > 0)
{
startPage = page.Value - 1;
}
vm.Employees = GetAllEmployeeData(startPage, vm.PageSize, sort);
vm.TotalRecords = context.TableEmployee.Count();
return View(vm);
}
public IEnumerable<Employees> GetAllEmployeeData(int page, int records, string sort)
{
IEnumerable<Employees> EmployeeData = null;
EmployeeData = context.TableEmployee.Where(e => e.IsActivated == true)
.Select(e => new Employees{ EmpID = e.EmpID, Name= e.Name, Joiningdate = e.Joiningdate , Department = e.DeptName}).AsEnumerable<Employees>();
switch (sort)
{
case "Department":
EmployeeData = EmployeeData .OrderBy(r => r.Department);
break;
case "JoiningDate":
EmployeeData = EmployeeData .OrderBy(r => r.JoiningDate);
break;
default:
EmployeeData = EmployeeData .OrderBy(r => r.Name);
break;
}
EmployeeData = EmployeeData .Skip(page * records).Take(records).ToList();
return EmployeeData ;
}
public ActionResult DeleteSelectedEmployee(int empId)
{
ContentsViewModel model = new ContentsViewModel();
int timelineItemId = 0;
EmployeeData E = context.TableEmployee.Find(empId);
context.TableEmployee.Remove(E);
context.SaveChanges();
return RedirectToAction("Index");
}
Here is my webgrid
@{var webgrid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
webgrid.Bind(Model.Employees, rowCount: Model.TotalRecords, autoSortAndPage: false);
webgrid.Pager(WebGridPagerModes.Numeric);
@webgrid.GetHtml(tableStyle: "webgridTable", htmlAttributes: new { id = "grid" },
columns: webgrid.Columns(
webgrid.Column("Name", "Name"),
webgrid.Column("Department", "Department"),
webgrid.Column("JoiningDate", "Join Date", format: @<text>@item.JoiningDate.ToString("dddd, MMMM d, yyyy")</text>),
webgrid.Column(header: "Action", format: (item) => Html.ActionLink("Edit", "Edit", new { empId = item.EmpID })),
webgrid.Column(format: (item) => Html.ActionLink("Delete", "Delete Record", new { empId = item.EmpID }))
));
}