ASP.net MVC CheckBoxFor casting error

前端 未结 1 1522
一生所求
一生所求 2020-12-11 15:01

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

相关标签:
1条回答
  • 2020-12-11 15:20

    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.

    0 讨论(0)
提交回复
热议问题