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:
- <div id="divStudentlist" style="height: 100px; overflow: auto; border: solid; width: 150px;">
- @foreach (var items in ViewData["Items"] as List
- <SelectListItem>) {
- <table width="100%">
- <tr>
- <td width="20px">
- <input type="checkbox" value="@items.Value" class="chkclass" />
- </td>
- <td width="100px">
- @items.Text
- </td>
- </tr>
-
- </table>
-
- }
- </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,
- var idslist = "";
-
- $("input:checkbox[class=chkclass]").each(function() {
-
- if ($(this).is(":checked")) {
- var userid = $(this).attr("value");
- idslist = idslist + userid + ',';
- }
-
- });
- $("#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:
- string[] i1;
- string items = frm["idlist"];
- if (items != null) {
- i1 = items.Split(new [] {
- ","
- }, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < i1.Length; i++) {
- string s = i1[i];
- }
- }