In this article I will explain with an example, how to call Controller’s Action method on CheckBox check event in ASP.Net MVC.
 
 
 

Model

The Model class consists of the following properties.
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 Table, which consists of a One HTML Input TextBox.
Html.CheckBoxFor – Creating CheckBox for the Model property.
Html.LabelFor - For displaying text.
 
Implementing check changed event in CheckBox
By default, there is no check changed event in CheckBox in ASP.Net MVC, hence JavaScript is required to implement it.
The 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_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, new {@id = "Form1" }))
    {
        <table>
            <tr>
                <td>@Html.CheckBoxFor(m => m.HasPassport, new {@onchange = "OnPassportChanged()" })</td>
                <td>@Html.LabelFor(m => m.HasPassport)</td>
            </tr>
        </table>
    }
    <script>
        function OnPassportChanged() {
            document.getElementById("Form1").submit();
        };
    </script>
</body>
</html>
 
 

Screenshots

The Form

ASP.Net MVC: Call Controller on CheckBox check event
 
 

Values captured in Controller when Form is submitted

ASP.Net MVC: Call Controller on CheckBox check event
 

Values captured in Controller when Form is unchecked

ASP.Net MVC: Call Controller on CheckBox check event
 
 

Downloads