How do I create a Checkbox using the Html.Checkboxfor Helper for a Nullable field?

Asked

Viewed 3,351 times

4

My field is as follows in my class:

public bool? meuCampo { get; set; }

And in my view it’s like this:

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

Only that way it’s not allowed, because I can’t explicitly convert the type bool? for bool, so to try to solve this I did the way below, using cast:

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

Then there is also an error which 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, there would be some other way to create checkboxes, using the Helper Html, with properties of the type Nullable<bool>?

2 answers

5

It is worth taking a look at Editortemplates from Asp.NET MVC. They have an implementation Coc (Convention over Configuration) standard. To configure you can create a template in:

Views Shared Editortemplates Boolean.cshtml

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

And use in your view:

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

Example: Extending Editor Templates for ASP.NET MVC

4

Yuri, the CheckBoxFor wait a bool, this pq o checked has only two states, selected or not.

optionally you can use the 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 attribution indeterminate:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.