Model
The Model class consists of the following property.
public class PersonModel
{
[Display(Name = "Do you have Passport?")]
public bool HasPassport { get; set; }
}
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside this Action method, the
HasPassport property is verified and based on whether
CheckBox is
checked or
unchecked, its value is true or false respectively.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
if (person.HasPassport)
{
}
return View();
}
}
View
HTML Markup
Inside the View, in the very first line the PersonModel class is declared as model for the View.
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.
The View also consists of an HTML Form which consists of:
CheckBox – Created using Html.CheckBoxFor Helper method.
Label – Created using Html.LabelFor for displaying text.
@model CheckBox_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>@Html.CheckBoxFor(m => m.HasPassport)</td>
<td>@Html.LabelFor(m => m.HasPassport)</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" /></td>
</tr>
</table>
}
</body>
</html>
Screenshots
The Form
Values captured in Controller when Form is submitted
Downloads