In this article I will explain with an example, how to implement
CheckBox check changed event in
ASP.Net Core (.Net Core 8) MVC.
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 IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult 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 and ASP.Net TagHelpers is inherited.
The View consists of an
HTML Form which has been created using the following
TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Input
CheckBox has been assigned with
asp-for Tag Helper attribute and its value is set with the
HasPassport property. Thus, this signifies that the validation will be performed for the
HasPassport property.
Then
Label has been assigned with
asp-for Tag Helper attribute and here also its value is set with the
HasPassport property which signifies that it is used for displaying the
Model property name.
Finally,
CheckBox has been assigned with an
onchange event handler, and when the
CheckBox is
checked or
unchecked, a
JavaScript function
OnPassportChanged submits the
Form and in turn calls the Controller’s Action method.
@model CheckBox_Changed_MVC_Core.Models.PersonModel
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post" id="Form1">
<table>
<tr>
<td><input asp-for="HasPassport" type="checkbox" onchange="OnPassportChanged()" /></td>
<td><label asp-for="HasPassport"></label></td>
</tr>
</table>
</form>
<script>
function OnPassportChanged() {
document.getElementById("Form1").submit();
};
</script>
</body>
</html>
Screenshots
The Form
Values captured in Controller when Form is submitted
Values captured in Controller when Form is unchecked
Downloads