My little world of sharing

Jun08

Delete multiple records in ASP.NET MVC 5

Delete multiple records in ASP.NET MVC 5

In this example I will show you how to delete multiple records from the database using checkbox. I have tried to make this example very simple and easy way so that anyone can implement this in a MVC application.

todo-1

I am using a ToDo sample application to explain this. This application has a simple data model called “ToDo”. Here is the code of my model.

Model

namespace MvcStore.Models
{
    public class AppModel
    {
             
        public class ToDo
        {
            public int Id { get; set; }
            public string Description { get; set; }
            public bool IsDone { get; set; }
            public virtual ApplicationUser User { get; set; }
        }
    }
}

Once I have the model setup off course I have to run and build the app to create the database. I am using default ApplicationDbContext which is provided at the time of application creation.

My table name is ToDoes, here is the code in the ApplicationDbContext class –

using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using MvcStore.ViewModels;
using System.Collections.Generic;

namespace MvcStore.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here

            return userIdentity;
        }


        // HomeTown will be stored in the same table as Users
        public string HomeTown { get; set; }

        public virtual ICollection<AppModel.ToDo> ToDoes { get; set; }

        // FirstName & LastName will be stored in a different table called MyUserInfo
        public virtual AppModel.MyUserInfo MyUserInfo { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

     
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public DbSet<Album> Albums { get; set; }
        public DbSet<Genre> Genres { get; set; }
        public DbSet<Artist> Artists { get; set; }
        public DbSet<Cart> Carts { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Auction> Auctions { get; set; }
        public DbSet<Bid> Bids { get; set; }

        public DbSet<AppModel.ToDo> ToDoes { get; set; }
        public DbSet<AppModel.MyUserInfo> MyUserInfo { get; set; }
        // public System.Data.Entity.DbSet<MvcStore.Models.ApplicationUser> ApplicationUsers { get; set; }


        //public DbSet<RoleViewModel> RoleViewModels { get; set; }
    }
}

Please note this class has other models that I have used for other tutorials. Just note the DbSet for ToDo class.

ToDoController

Now lets create the ToDoController. This controller will have some basic databaseĀ operations to add, remove, and update data from the database.

todo-2

I am just including the code for this delete and display all tasks for this controller below –

 [Authorize]
        public class ToDoController : Controller
        {
            private ApplicationDbContext db;
            private UserManager<ApplicationUser> manager;
            public ToDoController()
            {
                db = new ApplicationDbContext();
                manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
            }

            // GET: /ToDo/
            // GET ToDo for the logged in user
            public ActionResult Index()
            {
                var currentUser = manager.FindById(User.Identity.GetUserId());
                return View(db.ToDoes.ToList().Where(todo => todo.User.Id == currentUser.Id));
            }

 public ActionResult DeleteSelected(string[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                //throw error
                ModelState.AddModelError("", "No item selected to delete");
                return View();
            }

            //bind the task collection into list
            List<int> TaskIds = ids.Select(x => Int32.Parse(x)).ToList();

            for (var i = 0; i < TaskIds.Count(); i++)
            {
                var todo = db.ToDoes.Find(TaskIds[i]);
                //remove the record from the database
                db.ToDoes.Remove(todo);
                //call save changes action otherwise the table will not be updated
                db.SaveChanges();
            }
           
            //redirect to index view once record is deleted
            return RedirectToAction("Index");
        }
}

I have made this controller accessible for only Authorized users. You can remove the [Authorize] tag if you want to give access to everyone.

Index View

Right click on the controller and create a Index view to display all records. Modify the default code with the following codes.

@model IEnumerable<MvcStore.Models.AppModel.ToDo>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("DeleteSelected", "ToDo", FormMethod.Post))
{
<p>
    @Html.ActionLink("Create New", "Create", null, new { @class = "btn btn-primary" }) @Html.ActionLink("Show all", "all", null, new { @class = "btn btn-info" })
    <input type="submit" value="Delete Selected Students" onclick="return confirm('Are you sure you wish to delete selected Students?');" class="btn btn-danger" />
</p>

<table class="table table-bordered">
    <tr>
        <th>
            #
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.IsDone)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                <input type="checkbox" name="ids" value="@item.Id" />
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.IsDone)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "btn btn-sm btn-primary" }) 
                @Html.ActionLink("Details", "Details", new { id = item.Id }, new { @class = "btn btn-sm btn-info" }) 
                @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "btn btn-sm btn-danger" })
            </td>
        </tr>
    }
</table>



}

todo-3

I have used the form tag to post to the DeleteSelected action.

@using (Html.BeginForm("DeleteSelected", "ToDo", FormMethod.Post))
{
}

 

I have created a new item as highlighted above, I wanted to delete this by selecting the checkbox and clicking on the delete selected button.

todo-4

It prompts user when want to delete a record. If user click on OK then it will remove the records from the database and redirect to index view with updated result set.

todo-5

 

Happy programming!!!

 

1 Comment

  1. Dree18

    This helped me bigtime! šŸ˜€ Thanks a lot šŸ˜€

Leave a Comment

Your email address will not be published. Required fields are marked *