Handling CheckboxFor with a model

The irritating thing about the Checkboxfor in razor is that it does not return a true or false as one would expect and I did not care to change to an input and form element to handle this behavior.

Here is my solution

Add your CheckboxFor as you normally would when populating for a Model

  @Html.CheckBoxFor(model => model.Contractor, new { htmlAttributes = new { @type ="checkbox", })

In my controller I am returning the Model VisitorAccess including a bool for Contractor

   public ActionResult Visit(VisitorAccess vis) {


            var isChecked = Request.Form["Contractor"];

              if (!isChecked.Equals("false"))
            {
                //Checkbox is checked, do whatever you want!
                myModel.Contractor = true;
            }
            else
            {
                myModel.Contractor = false;

            }
....

What makes this work is that it returns either "false" or "false,false"
             

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax