简体   繁体   中英

Nullable Object Must Have a Value ASP.NET MVC 5 Checkbox For

Hi I have a CheckBox For

@Html.CheckBoxFor(model => model.VisitRequested.Value, new {onClick = "showHide();"})

It throws the exception (above) if the checkbox isn't clicked. I would like the value to be 0 or false if the check box remains unchecked.

The model code is:

[DisplayName("Request a Visit")]
public Nullable<bool> VisitRequested { get; set; }

The Value property of a Nullable<T> throws an InvalidOperationException when the value is null (actually when HasValue == false ). Try:

@Html.CheckBoxFor(model => model.VisitRequested, new {onClick = "showHide();"}) 

Just use model.VisitRequested and eventually wrap it inside an if :

@if (Model.VisitRequested.HasValue)
{
   @Html.CheckBoxFor(model => model.VisitRequested, new {onClick = "showHide();"}) 
}

Yes that's because model.HasValue is false. Add;

 if (model.VisitRequested.HasValue)
    @Html.CheckBoxFor(model => model.VisitRequested.Value, new {onClick = "showHide();"});
 else
    //somethings wrong, not sure what you want to do

Basically that is indicating that the object is null. In the docs you'll find;

Exception:
InvalidOperationException Condition:
The HasValue property is false

which is what you're encountering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM