Checkbox list in ASP.Net MVC
Recently, I got an assignment when
I need to show the items in checkbox list format. It was very easy in ASP.NET
web form because it has CheckBoxList control but it was bit challenging for me
to show the items in checkbox list in ASP.NET MVC as there are basic controls
available.
In this post I am going to explain
you how to build the CheckBoxList control in ASP.NET MVC using the basic
control and Razor engine following the steps listed below. Let’s get started
Step 1. First thing first, View Code
@model SOW.Models.DropdownValues
<table>
<tr>
<td class="td_12per">Select
Country:</td>
<td class="td_12per">
<div class="divCheckbox" id="divSelCountry">
@foreach (var item in Model.SendingCountryList)
{
<div class="checkbox" style="border:1px solid gray; margin-top:-1px;margin-bottom:0px;width:100%;padding-left:2px">
<label>
<input type="checkbox"
name="SelectedItems"
value="@item.Value" id="SCL_@item.Value" /> @item.Text
</label>
</div>
}
</div>
</td>
</tr>
</table>
Step 2. Model
public class DropdownValues
{
public DropdownValues()
{
CountryList
= new List<SelectListItem>();
}
public IList<SelectListItem>
SendingCountryList { get; set; }
}
Step 3. Controller – Create a
controller name CheckboxListController
public class CheckboxListController : Controller
{
// GET:
AnnualReview
public ActionResult CheckboxList()
{
DropdownValues dv = new DropdownValues();
//Sending
Country List
dv.CountryList.Add(new SelectListItem { Text
= "Select All", Value = "SelectAll" });
dv.
CountryList.Add(new SelectListItem { Text = "Australia
Australia Australia Australia", Value = "Australia" });
dv.
CountryList.Add(new SelectListItem { Text = "Austria", Value = "Austria" });
return View("ViewName", dv);
}
}
Step 4. Final Output

Comments