Search code examples
asp.net-mvccheckboxfor

ASP.net MVC CheckBoxFor casting error


I have a EF entity that is tied to a SQL table that contains a bit field called "Active". I generate the Edit code from the T4 template, and the page inherits from the EF entity. At the bottom of the page, it generated a CheckBoxFor like this:

<%= Html.CheckBoxFor(model => model.Active) %>

I get the wonderful red squiggly under model.Active, and the error message says that I cannot implicitly convert type bool? to bool. So, I tried the following:

<%= Html.CheckBoxFor(model => (bool)model.Active) %>

It, of course, didn't like that and gave me this error:

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

I'm probably missing something simple.


Solution

  • Try model.Active.Value

    If this field should be not nullable then you should change data type on database side to not null.

    EDIT

    Why does this happen?

    Your database field is defined as FIELDNAME BIT NULL. It means that it can contain three values: NULL, true and false. Since it can contain three values, it is mapped to bool? type in entity framework. bool? is another name of Nullable<bool>, which is wrapper around bool allowing it to have third value: NULL. Since CheckBoxFor expects one of two values - true or false, it can't except Nullable<bool>. Every Nullable has property called value which returns wrapped type. But you should be aware that when database field will contain null Nullable<bool>.Value will throw an error. If you are sure that this field should not contain NULL values, you should change it's data type to FIELDNAME BIT NOT NULL and generate model from database again. This will change data type from bool? to bool and there willbe no need to call Value property.