Reputation: 1651
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; }
Upvotes: 2
Views: 8066
Reputation: 46551
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();"})
}
Upvotes: 3
Reputation: 48096
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.
Upvotes: 0