In this article we learn a step by step process, How to Create Multi Select dropdownlist with checkboxes in Asp.Net Core C#.
Prerequisites
- Download and install .Net Core 6.0 SDK from here
- Download and Install Microsoft Visual Studio 2022 from here
Create an Asp.Net Core Web App
- Open visual studio and click the Create New Project Option
- Select the Template
- Enter the name of the Application
Install NuGet Packages
- Microsoft Entity Framework Core Sql Server.
- Microsoft Entity Framework Core Tools
Configure appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "sqlconnection": "Server=(local)\\MSSQL;Database=Inventory;Trusted_Connection=True;MultipleActiveResultSets=true", }, "AllowedHosts": "*" }
Create Model
Create Model class, viewmodel class and DbContext Class.
//Country.cs
using System.ComponentModel.DataAnnotations; namespace Asp.netcore_Tutorials.Models { public class Country { [Key] public int countryId { get; set; } public string countryName { get; set; } } }
countryModel.cs
using Microsoft.AspNetCore.Mvc.Rendering; namespace Asp.netcore_Tutorials.Models { public class countryModel { public int countryId { get; set; } public string countryName { get; set; } public List<SelectListItem> Countrys { get; set; } public int[] CountryIds { get; set; } } }
CustDbcontext.cs
//CustDbcontext.cs using Microsoft.EntityFrameworkCore; namespace Asp.netcore_Tutorials.Models { public class CustDbcontext :DbContext { public CustDbcontext(DbContextOptions<CustDbcontext> options):base(options) { } public virtual DbSet<Country> Countries { get; set; } } }
Create Interface and Concrete Class
Interface ICustomer.cs
using System.Data; namespace Asp.netcore_Tutorials.Repository { public interface IInventory { Task<IEnumerable<Country>> Getcountries(); } }
Concrete Class Customerdetail.cs
using Microsoft.AspNetCore.Http; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; using System.IO; namespace Asp.netcore_Tutorials.Repository { public class Inventory : IInventory { private readonly CustDbcontext _IvenContext; public Inventory(CustDbcontext custDbcontext) { _IvenContext = custDbcontext; } public async Task<IEnumerable<Country>> Getcountries() { return await _IvenContext.Countries.ToListAsync(); } } }
Configure Program.cs
using Asp.netcore_Tutorials.Models; using Asp.netcore_Tutorials.Repository; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System.Configuration; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<CustDbcontext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection"))); builder.Services.AddScoped<ICustomer,CustomerDetail>(); builder.Services.AddScoped<IInventory, Inventory>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
Migration
Add-Migration 'Initial-Create' Update-Database
Also check my previous Articles Implement JWT Authentication in Asp.Net Core Web API
Create Controller
InventoryController.cs
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Asp.netcore_Tutorials.Repository; using Microsoft.AspNetCore.Mvc.Rendering; using Asp.netcore_Tutorials.Models; namespace Asp.netcore_Tutorials.Controllers { public class InventoryController : Controller { // GET: InventoryController private readonly IInventory _Ivencontext; public InventoryController(IInventory ivencontext) { _Ivencontext = ivencontext; } public ActionResult Index() { countryModel country = new countryModel(); country.Countrys = _Ivencontext.Getcountries().Result.Select(k => new SelectListItem { Text = k.countryName, Value = Convert.ToString(k.countryId) }).ToList(); return View(country); } [HttpPost] public IActionResult Multiselect(countryModel country) { var countriesid = country.CountryIds; var model = _Ivencontext.Getcountries().Result.Where(p => countriesid.Contains(p.countryId)); return Ok(); } } }
Customize View
index.cshtml
@*@{ ViewData["Title"] = "Home Page"; }*@ @model Asp.netcore_Tutorials.Models.countryModel <html> <head> <script src="~/js/jquery.js"></script> <link href="~/css/bootstrap.min.css" rel="stylesheet" /> <script src="~/js/bootstrap.min.js"></script> <script src="~/js/bootstrap-multiselect.js"></script> <link href="~/css/bootstrap-multiselect.css" rel="stylesheet" /> </head> <body> <form asp-controller="Inventory" asp-action="Multiselect" method="post"> <div class="row"> <div class="form-group"> <div class="col-sm-4"> @Html.ListBoxFor(model=> model.CountryIds,Model.Countrys, new {@class="form-control",id="Country", multiple="multiple" }) </div> </div> </div> <input class="btn btn-primary" type="submit" value="Submit" /> </form> <script> $(function () { $('#Country').multiselect({ includeSelectAllOption : true, }); }); </script> </body> </html>
Can you share me the Code please