Delete Selected Rows From Grid With Confirmation Message In MVC 5

Here are the steps, 

Step 1: Create a basic project MVC with Controller, Model and View.

Model and View

Step 2: Include required query libraries.

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.

Code
  1. @using (Html.BeginForm("DeleteSelected""GetStudents", FormMethod.Post))    
  2. {    
  3.     <div>    
  4.         @grid.GetHtml(    
  5.     
  6.         tableStyle: "gridtable",    
  7.         columns:    
  8.         grid.Columns    
  9.         (    
  10.             grid.Column(format:@<text><input type="checkbox" name="ids" value="@item.ID" /></text>, header: "Select"),    
  11.             grid.Column("ID""Stud ID"),    
  12.             grid.Column("Name""Stud Name"),    
  13.             grid.Column("Class""Class"),    
  14.             grid.Column("Section""Section"),    
  15.             grid.Column("Address""Address"),    
  16.             grid.Column("Email""Email"),    
  17.             grid.Column("Percentage""Percentage")    
  18.             ), mode: WebGridPagerModes.Numeric)    
  19.     
  20.     
  21.     </div>    
  22.     <input type="submit" value="Delete Selected Students" onclick = "return confirm('Are you sure you wish to delete selected Students?');"  />    
  23. }   
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:
  1. public ActionResult DeleteSelected(string[] ids)  
  2. {  
  3.     if (ids == null || ids.Length == 0)  
  4.     {  
  5.         StudentDetailsModel objuserloginmodel = TempData["formData"as StudentDetailsModel;  
  6.         TempData["formData"] = objuserloginmodel;  
  7.         return View("Index", objuserloginmodel);  
  8.     }  
  9.     List < int > UserIds = ids.Select(x => Int32.Parse(x))  
  10.         .ToList();  
  11.     StudentDetailsModel _objuserloginmodel = TempData["formData"as StudentDetailsModel;  
  12.     _objuserloginmodel.Studentmodel = _objuserloginmodel.Studentmodel.Where(a => !UserIds.Contains(a.Id))  
  13.         .ToList();  
  14.     TempData["formData"] = _objuserloginmodel;  
  15.     return View("Index", _objuserloginmodel);  
  16. }  
Step 5: Build application and run it. You will find it as in the following screenshot,

index

Hope you will understand how we can delete rows from grid. Added code will help you to understand in more detail. 

Up Next
    Ebook Download
    View all
    Learn
    View all