Here are the steps,
Step 1: Create a basic project MVC with Controller, Model and View.
Step 2: Include required query libraries.
Step 3: Add grid with required column and also mention the Controller and Action to be called on button click. Add the button as well and also add Confirmation message.
- @using (Html.BeginForm("DeleteSelected", "GetStudents", FormMethod.Post))
- {
- <div>
- @grid.GetHtml(
-
- tableStyle: "gridtable",
- columns:
- grid.Columns
- (
- grid.Column(format:@<text><input type="checkbox" name="ids" value="@item.ID" /></text>, header: "Select"),
- grid.Column("ID", "Stud ID"),
- grid.Column("Name", "Stud Name"),
- grid.Column("Class", "Class"),
- grid.Column("Section", "Section"),
- grid.Column("Address", "Address"),
- grid.Column("Email", "Email"),
- grid.Column("Percentage", "Percentage")
- ), mode: WebGridPagerModes.Numeric)
-
-
- </div>
- <input type="submit" value="Delete Selected Students" onclick = "return confirm('Are you sure you wish to delete selected Students?');" />
- }
Step 4: Add the action code. Add linq that if selected rows are present remove those.
Note: I haven’t use any database call. You may use database in that case you must use deleted from db call.
My action is as below:
- public ActionResult DeleteSelected(string[] ids)
- {
- if (ids == null || ids.Length == 0)
- {
- StudentDetailsModel objuserloginmodel = TempData["formData"] as StudentDetailsModel;
- TempData["formData"] = objuserloginmodel;
- return View("Index", objuserloginmodel);
- }
- List < int > UserIds = ids.Select(x => Int32.Parse(x))
- .ToList();
- StudentDetailsModel _objuserloginmodel = TempData["formData"] as StudentDetailsModel;
- _objuserloginmodel.Studentmodel = _objuserloginmodel.Studentmodel.Where(a => !UserIds.Contains(a.Id))
- .ToList();
- TempData["formData"] = _objuserloginmodel;
- return View("Index", _objuserloginmodel);
- }
Step 5: Build application and run it. You will find it as in the following screenshot,
Hope you will understand how we can delete rows from grid. Added code will help you to understand in more detail.