Pages

How to delete multiple records from webgrid in mvc

Tuesday, 11 November 2014
In this post, I'll explain how to delete multiple record from webgrid .
Step 1- Create a new empty mvc project.
Step 2- Add Model class Employee and Context Class to model folder.
public class Employee
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }
public class DemoContext:DbContext
    {
        public DbSet<Employee> Employee { get; set; }
    }

Step 3- Add a new controller and write the following to populate webgrid
 public class HomeController : Controller
    {
        DemoContext _db = new DemoContext();
        public ActionResult Index()
        {
            var getData=_db.Employee.ToList();
            return View(getData);
        }
    }

step 4- Build the solution then add a strongly typed view name as Index. write down following code to your view
@model IEnumerable<MultipleDelete.Models.Employee>


@{
    ViewBag.Title = "Index";
    var grid = new WebGrid(source: Model, rowsPerPage: 5);
}
<h2>Employee List</h2>
<div id="divList">
    @using(Html.BeginForm("DeleteSelected", "Home",FormMethod.Post))
    {
        @grid.GetHtml(
    columns:
        grid.Columns(
               grid.Column(format: @<text><input type="checkbox" name="Eid" value="@item.ID" /></text>, header: ""),
                grid.Column("ID", "ID"),
                grid.Column("Name", "Name"),
                grid.Column("Position", "Position"),
                grid.Column("Age", "Age"),
                grid.Column("Salary", "Salary")
            )
        )
        <input type="submit" value="Delete" />
    }
</div>

Step -5 Add a Action to your controller which delete selected records.
         [HttpPost]
        public ActionResult DeleteSelected(string[] Eid)
        {
            var SelectCount=Eid.Length;
            List<int> selectedIds=new List<int>();
            foreach (var d in Eid)
            {
                selectedIds.Add(Convert.ToInt32(d));
            }
            IList<Employee> selectedEmployee = new List<Employee>();
            selectedEmployee = _db.Employee.Where(n => selectedIds.Contains(n.ID)).ToList();
            foreach(var singleEmp in selectedEmployee)
            {
                _db.Employee.Remove(singleEmp);
            }
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

what I'm doing in above action is as follow

First I got the array of string of ID's from posted form, then I converted it into int array.

Then I get the list of employee from corresponding Id's , then using foreach loop I have deleted it one by one.

Click Here to get Above Code Download

No comments:

Post a Comment