How can I create a CheckBox using the Html.CheckBoxFor Helper for a Nullable field?

4

My field is as follows in my class:

public bool? meuCampo { get; set; }

And in my view it looks like this:

@Html.CheckBoxFor(m => m.meuCampo)

But this way it is not allowed, because I can not explicitly convert type bool? to bool , so to try to solve this I did it in the form below, using cast :

@Html.CheckBoxFor(m => (bool)m.meuCampo)

To do this, so also occurs an error that is as follows:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

So according to the facts, would you have any other way to create a checkbox, using Helper Html , with properties of type Nullable<bool> ?

    
asked by anonymous 09.05.2016 / 18:10

2 answers

5

It pays to take a look at Asp.NET MVC EditorTemplates. They have a standard CoC (Convention over Configuration) implementation. To configure you can create a template in:

Views \ Shared \ EditorTemplates \ Boolean.cshtml

@model Boolean?
@Html.CheckBox("", Model.HasValue && Model.Value)

And use it in your view:

@Html.EditorFor(m => m)
@Html.LabelFor(m => m)

Example: Extending Editor Templates for ASP. NET MVC

    
09.05.2016 / 18:30
4

Yuri, CheckBoxFor expects a bool, this because checked has only two states, selected or not.

Optionally you can use HtmlHelper.CheckBox and enter the property name as string.

@Html.CheckBox("meuCampo", Model.HasValue && Model.Value)

If you really need to work with three states, use the indeterminate attribute:

@{
dynamic htmlAttributes = new ExpandoObject();
if (!Model.HasValue)
    htmlAttributes.indeterminate = "indeterminate";
}
@Html.CheckBox("meuCampo", Model.HasValue && Model.Value, htmlAttributes as IDictionary<string, Object>;)
    
09.05.2016 / 18:27