[asp.net-mvc] Proper usage of .net MVC Html.CheckBoxFor

All I want to know is the proper syntax for the Html.CheckBoxFor HTML helper in ASP.NET MVC.

What I'm trying to accomplish is for the check-box to be initially checked with an ID value so I can reference it in the Controller to see if it's still checked or not.

Would below be the proper syntax?

@foreach (var item in Model.Templates) 
{ 
    <td> 
        @Html.CheckBoxFor(model => true, item.TemplateId) 
        @Html.LabelFor(model => item.TemplateName)
    </td> 
}

This question is related to asp.net-mvc checkboxfor

The answer is


I was looking for the solution to show the label dynamically from database like this:

checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database

So none of the above solution worked for me so I used like this:

 @Html.CheckBoxFor(m => m.Option1, new { @class = "options" }) 
 <label for="Option1">@Model.Option1Text</label>

 @Html.CheckBoxFor(m => m.Option2, new { @class = "options" }) 
 <label for="Option2">@Mode2.Option1Text</label>

In this way when user will click on label, checkbox will be selected.

Might be it can help someone.


I was having a problem with ASP.NET MVC 5 where CheckBoxFor would not check my checkboxes on server-side validation failure even though my model clearly had the value set to true. My Razor markup/code looked like:

@Html.CheckBoxFor(model => model.MyBoolValue, new { @class = "mySpecialClass" } )

To get this to work, I had to change this to:

@{
    var checkboxAttributes = Model.MyBoolValue ?
        (object) new { @class = "mySpecialClass", @checked = "checked" } :
        (object) new { @class = "mySpecialClass" };
}
@Html.CheckBox("MyBoolValue", checkboxAttributes)

None of the above answers worked for me when binding back on POST, until I added the following in CSHTML

<div class="checkbox c-checkbox">
    <label>
        <input type="checkbox" id="xPrinting" name="xPrinting" value="true"  @Html.Raw( Model.xPrinting ? "checked" : "")>
        <span class=""></span>Printing
    </label>
</div>


// POST: Index

[HttpPost]
public ActionResult Index([Bind(Include = "dateInHands,dateFrom,dateTo,pgStatus,gpStatus,vwStatus,freeSearch,xPrinting,xEmbroidery,xPersonalization,sortOrder,radioOperator")] ProductionDashboardViewModel model)

I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.

Instead of:

@Html.CheckBoxFor(model => true, item.TemplateId) 

Format html helper like so:

@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})

Then in the viewmodel/model wherever your logic is:

public void Save(FormCollection frm)
{   
    // to do instantiate object.

    instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);

    // to do and save changes in database.
}

By default, the below code will NOT generate a checked Check Box as model properties override the html attributes:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

Instead, in your GET Action method, the following needs to be done:

model.SomeBooleanProperty = true;

The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).

However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.

 @Html.CheckBox("SomeBooleanProperty", new { @checked = "checked" });

UPDATE

//Get Method
   public ActionResult CreateUser(int id)
   {
        model.SomeBooleanProperty = true;         
   }

Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.


Place this on your model:

[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }

private string electricFanRate;

public string ElectricFanRate
{
    get { return electricFanRate ?? (electricFanRate = "$15/month"); }
    set { electricFanRate = value; }
}

And this in your cshtml:

<div class="row">
    @Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
    @Html.LabelFor(m => m.ElectricFan, new { @class = "" })
    @Html.DisplayTextFor(m => m.ElectricFanRate)
</div>

Which will output this:

MVC Output If you click on the checkbox or the bold label it will check/uncheck the checkbox