Introduction
In this article we will learn how to bind checkbox in Asp.net MVC using Model class. Bind checkbox using model using MVC.
ASP.Net MVC does not have an in-built CheckBox control and hence using the SelectListItem class as Model, a Custom CheckBox has been populated from Model Class.
Model :- Here is my model class code named as CheckboxListModel. Here i use SelectListItem to store the values of total Games.
public class CheckBoxListModel
{
public IList<string> SelectedGames { get; set; }
public IList<SelectListItem> AvailableGames { get; set; }
public CheckBoxListModel()
{
SelectedGames = new List<string>();
AvailableGames = new List<SelectListItem>();
}
}
|
Note : you can use database data as well by replacing the static data from this method.
public class CheckBoxListController : Controller
{
// GET: CheckBoxList
public ActionResult Index()
{
var model = new CheckBoxListModel
{
AvailableGames = GetGames()
};
return View(model);
}
private IList<SelectListItem> GetGames()
{
List<SelectListItem> objList = new List<SelectListItem>() {
new SelectListItem {Text = "Cricket", Value = "Cricket"},
new SelectListItem {Text = "Football", Value = "Football"},
new SelectListItem {Text = "Table Tennis", Value = "Table Tennis"},
new SelectListItem {Text = "Hockey", Value = "Hockey"},
};
return objList;
}
}
|
he View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside this form a foreach loop is used to bind the iterated List of data to the Checkbox.
@model MVCDemo.Models.CheckBoxListModel
@{
ViewBag.Title = "Index";
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="container">
@using (Html.BeginForm("Index", "Home"))
{
foreach (var item in Model.AvailableGames)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="SelectedFruits"
value="@item.Value" /> @item.Text
</label>
</div>
}
}
</div>
</body>
</html>
|
Output:
0 comments:
Post a Comment