MultiCheckbox In ASP.NET MVC

In this article we are going to create a form with a multi-checkboxes option and on form submit store the values.

ASP.NET

You will learn more about the following things,

  • What is FormCollection and its uses?
  • How to do ViewBag stored LIST object iteration
  • How to iterate collections of CheckBoxes which are marked as checked

What is FormCollection and Its Uses?

FormCollection class is part of  System.Web.MVC .

FormCollection is another way to access the form element in action method of the controller.

Example

  1. [HttpPost]  
  2.         //Here are we had set to receive two parameter FormCollection and Model  
  3.         public ActionResult InsertMember(FormCollection formval, MemberEntryModel _mod)  
  4.         {  
  5.             var db = new MultiBoxDataClassesDataContext();  
  6.             ViewBag.lstSkills = (from a in db.tblSkills select a).ToList();  
  7.             return View();  
  8.         }  

How to do ViewBag stored LIST object iteration?

ViewBag is used for transferring the value from Controller to View.

Example

  1. //Created ViewBag for transferring SKILL list.  
  2. var db = new MultiBoxDataClassesDataContext();  
  3. ViewBag.lstSkills = (from a in db.tblSkills select a).ToList();  

How to iterate collection of CheckBoxes which are marked as checked?

  1. //Iterating the collection of checkboxes which checked marked  
  2.         $('input[type=checkbox]').each(function () {  
  3.             if (this.checked) {  
  4.                 abc = abc + $(this).val() + ","  
  5.                 //assign set value to hidden field   
  6.                  $('#SkillID').val(abc);  
  7.             }  
  8.         });  

Now back to implementation of the task

Before creating a project now we are going to create a table where we are going to store selected checkbox values.

We are going to create three tables,

SR. NO. TABLE NAME DESCRIPTION
1 tblSkills To manage various types of skills.
2 tblMembers To manage members information.
3 tblMemberSkills To manage members skills.
  1. tblSkills structure
    1. CREATE TABLE tblSkills (  
    2.     SkillID int NOT NULL  PRIMARY KEY Identity,  
    3.     Title varchar(50),  
    4. );  
  1. tblMembers structure
    1. CREATE TABLE [dbo].[tblMembers](  
    2.     [MemberID] [int] IDENTITY(1,1) NOT NULL,  
    3.     [MemberName] [varchar](50) NULL,  
    4.     [Address] [varchar](50) NULL,  
    5.     [City] [varchar](50) NULL,  
    6. PRIMARY KEY CLUSTERED   
    7. (  
    8.     [MemberID] ASC  
    9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
    10. ON [PRIMARY]  
  1. tblMemberSkills structure,
    1. CREATE TABLE tblMemberSkills (  
    2.     MemberSkillID int NOT NULL  PRIMARY KEY Identity,  
    3.     SkillID int,  
    4.     MemberID int  
    5. );  

Now insert some data/records into tblSkills

  1. insert into tblSkills (title) values('Visual Foxpro')  
  2. insert into tblSkills (title) values('C#')  
  3. insert into tblSkills (title) values('VB.NET')  
  4. insert into tblSkills (title) values('Delphi')  
  5. insert into tblSkills (title) values('Java')  
  6. insert into tblSkills (title) values('Power Builder')  
  7. insert into tblSkills (title) values('COBOL')  
  8. insert into tblSkills (title) values('Python')  

In tblMembers and tblMemberSkills we save the data through coding.

I am using Visual Studio 2015

ASP.NET

ASP.NET

ASP.NET

ASP.NET 

Now your screen should look like this:

ASP.NET

We had created a project called “ “now we are going to add Linq to SQL Class

ASP.NET

Now right click on Project name or icon --->Add-->New Item

or

Simply press Ctrl + Shift + A  (To add a new item from the dialog box)

ASP.NET

I gave it the name “MultiBoxDataClasses.dbml”

Server explorer can be visible / ON  by pressing CTRL+ALT+S.  Now click on Server Explorer and establish your connection with sql server.

Drag  and drop your table on MultiBoxDataClasses.dbml file canvas.

ASP.NET

Now switch to solution explorer again and right click on MODELS folder and insert a CLASS file. Give the class file name “MemberEntryModel.cs”

ASP.NET
 
ASP.NET

Now switch to solution explorer again and double click on CONTROLLERS folder then HomeController.cs.

In this we are not going to create separate controller for our task we will use HOME controller.

Create an two InsertMember method in HomeController.cs

  1. HttpGet
  2. HttpPost
  • HttpGet - This method will get executed first time in url call.
  • HttpPost - This method will get executed while form submitted.

Example

  1. [HttpGet]  
  2.         public ActionResult InsertMember()  
  3.         {  
  4.             //Created ViewBag for transferring SKILL list.  
  5.             var db = new MultiBoxDataClassesDataContext();  
  6.             ViewBag.lstSkills = (from a in db.tblSkills select a).ToList();  
  7.   
  8.             return View();  
  9.         }  
  10.   
  11.         [HttpPost]  
  12.         //Here are we had set to receive two parameter FormCollection and Model  
  13.         public ActionResult InsertMember(FormCollection formval, MemberEntryModel _mod)  
  14.         {  
  15.             var db = new MultiBoxDataClassesDataContext();  
  16.             ViewBag.lstSkills = (from a in db.tblSkills select a).ToList();  
  17.             return View();  
  18.         }  

Now right click on HttpGet InsertMember method and select ADD VIEW option

ASP.NET

ASP.NET

You can check InsertMember.cshtml created in Views-->Home folder

ASP.NET

We had removed SkillID default code just after city field code and changed the following code.

  1. @*Foreach loop on VIEWBAG which received from controller.*@  
  2.        @foreach (var skill in ViewBag.lstSkills)  
  3.        {  
  4.            <div style="padding-right:15px;margin-left:200px" >  
  5.                <input id="@skill.SkillID" type="checkbox" name="skill" value="@skill.SkillID" />  
  6.                <label for="@skill.SkillID">  
  7.                    @skill.Title  
  8.                </label>  
  9.            </div>  
  10.        }  
  11.                                          
  12.        </div>  
  13.        @Html.HiddenFor(model => model.SkillID)  
  14.        <br />  
  15.        <div class="form-group">  
  16.            <div class="col-md-offset-2 col-md-10">  
  17.                @*onclick calling UPDATEMARK function   
  18.                which set assign the selected checkbox value to hidden field*@  
  19.                <input type="submit" value="Create" class="btn btn-default" onclick="updatemark()" />  
  20.            </div>  
  21.        </div>  

Javascript Function  UPDATEMARK()

  1. <script>  
  2.     function updatemark(arg)  
  3.     {  
  4.         var abc = ""  
  5. //Iterating the collection of checkboxes which checked marked  
  6.         $('input[type=checkbox]').each(function () {  
  7.             if (this.checked) {  
  8.                 abc = abc + $(this).val() + ","  
  9.                 //assign set value to hidden field   
  10.                  $('#SkillID').val(abc);  
  11.             }  
  12.         });  
  13.           
  14.     }  
  15. </script> 

CODE of INSERTMEMBER.CSHTML

  1. @model CheckboxSampleAspNetMvc.Models.MemberEntryModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "InsertMember";  
  5. }  
  6.   
  7. <h2>InsertMember</h2>  
  8. <hr />  
  9. @using (Html.BeginForm())   
  10. {  
  11.     @Html.AntiForgeryToken()  
  12.       
  13.     <div class="form-horizontal">  
  14.   
  15.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.MemberID, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.MemberID, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.MemberID, ""new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.   
  24.         <div class="form-group">  
  25.             @Html.LabelFor(model => model.MemberName, htmlAttributes: new { @class = "control-label col-md-2" })  
  26.             <div class="col-md-10">  
  27.                 @Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { @class = "form-control" } })  
  28.                 @Html.ValidationMessageFor(model => model.MemberName, ""new { @class = "text-danger" })  
  29.             </div>  
  30.         </div>  
  31.   
  32.         <div class="form-group">  
  33.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  34.             <div class="col-md-10">  
  35.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  36.                 @Html.ValidationMessageFor(model => model.Address, ""new { @class = "text-danger" })  
  37.             </div>  
  38.         </div>  
  39.   
  40.         <div class="form-group">  
  41.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  42.             <div class="col-md-10">  
  43.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
  44.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  45.             </div>  
  46.         </div>  
  47.          
  48.             @*Foreach loop on VIEWBAG which received from controller.*@  
  49.             @foreach (var skill in ViewBag.lstSkills)  
  50.             {  
  51.                 <div style="padding-right:15px;margin-left:200px" >  
  52.                     <input id="@skill.SkillID" type="checkbox" name="skill" value="@skill.SkillID" />  
  53.                     <label for="@skill.SkillID">  
  54.                         @skill.Title  
  55.                     </label>  
  56.                 </div>  
  57.             }  
  58.                                               
  59.             </div>  
  60.             @Html.HiddenFor(model => model.SkillID)  
  61.             <br />  
  62.             <div class="form-group">  
  63.                 <div class="col-md-offset-2 col-md-10">  
  64.                     @*onclick calling UPDATEMARK function   
  65.                     which set assign the selected checkbox value to hidden field*@  
  66.                     <input type="submit" value="Create" class="btn btn-default" onclick="updatemark()" />  
  67.                 </div>  
  68.             </div>  
  69. }  
  70.   
  71. <script>  
  72.     function updatemark(arg)  
  73.     {  
  74.         var abc = ""  
  75. //Iterating the collection of checkboxes which checked marked  
  76.         $('input[type=checkbox]').each(function () {  
  77.             if (this.checked) {  
  78.                 abc = abc + $(this).val() + ","  
  79.                 //assign set value to hidden field   
  80.                  $('#SkillID').val(abc);  
  81.             }  
  82.         });  
  83.           
  84.     }  
  85. </script>  
  86. <div>  
  87.     @Html.ActionLink("Back to List""Index")  
  88. </div>  
  89.   
  90. @section Scripts {  
  91.     @Scripts.Render("~/bundles/jqueryval")  
  92. }  

Select InsertMember.csthml and  Press F5 to execute the project or manually type

http://localhost:xxxxx/Home/InsertMember

Xxxxx = Your project port number.

OUTPUT

ASP.NET

FILL IN THE FORM

ASP.NET

After submitting form by pressing CREATE button:

ASP.NET

Mark BreakPoint in HTTPPOST method:

ASP.NET

FormCollection

ASP.NET


Similar Articles