asp.net-mvc-3razornullable

Checkbox for nullable boolean


My model has a boolean that has to be nullable

public bool? Foo
{
   get;
   set;
}

so in my Razor cshtml I have

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

except that doesn't work. Neither does casting it with (bool). If I do

@Html.CheckBoxFor(m => m.Foo.Value)

that doesn't create an error, but it doesn't bind to my model when posted and foo is set to null. Whats the best way to display Foo on the page and make it bind to my model on a post?


Solution

  • I got it to work with

    @Html.EditorFor(model => model.Foo) 
    

    and then making a file at Views/Shared/EditorTemplates/Boolean.cshtml with the following:

    @model bool?
    
    @Html.CheckBox("", Model.GetValueOrDefault())