Multi-Select Dropdown With Checkbox In MVC 4

Step 1: MVC set Viewdata in controller inside save get method using foreach loop.

Step 2: Inside View write foreach loop for multiselect dropdown with checkboxlist. Here's the code snippet:

  1. <div id="divStudentlist" style="height: 100px; overflow: auto; border: solid; width: 150px;">  
  2.     @foreach (var items in ViewData["Items"as List  
  3.     <SelectListItem>) {  
  4.         <table width="100%">  
  5.             <tr>  
  6.                 <td width="20px">  
  7.                     <input type="checkbox" value="@items.Value" class="chkclass" />  
  8.                 </td>  
  9.                 <td width="100px">  
  10.                     @items.Text  
  11.                 </td>  
  12.             </tr>  
  13.   
  14.         </table>  
  15.   
  16.         }  
  17. </div>  
Step 3: Now the question arises, how will you send your selected items values to controller because once you get the values into the controller, you can do anything like save into database. So let’s understand the following jQuery code.

Before that, you should place @Html.Hidden("idlist") inside Ajax.BeginForm and now write jQuery,
  1. var idslist = "";  
  2.   
  3. $("input:checkbox[class=chkclass]").each(function() {  
  4.   
  5.     if ($(this).is(":checked")) {  
  6.         var userid = $(this).attr("value");  
  7.         idslist = idslist + userid + ',';  
  8.     }  
  9.   
  10. });  
  11. $("#idlist").val(idslist);  
Step 4: Inside controller add/save post method should have the following parameter: (FormCollection frm) and then write the following c# code:
  1. string[] i1;  
  2. string items = frm["idlist"];  
  3. if (items != null) {  
  4.     i1 = items.Split(new [] {  
  5.         ","  
  6.     }, StringSplitOptions.RemoveEmptyEntries);  
  7.     for (int i = 0; i < i1.Length; i++) {  
  8.         string s = i1[i]; /*Inside string type s variable should contain items values */  
  9.     }  
  10. }  
Ebook Download
View all
Learn
View all