2

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; }
ASPCoder1450
  • 1,651
  • 4
  • 23
  • 47
  • possible duplicate of [MVC3: Creating checkbox for nullable boolean](http://stackoverflow.com/questions/6849774/mvc3-creating-checkbox-for-nullable-boolean) – hazzik Mar 05 '14 at 20:51

2 Answers2

3

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();"}) 
}
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
0

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • model does not exist in the current context. Do I have to use @{} symbols for the code? – ASPCoder1450 Mar 05 '14 at 18:09
  • @ASPCoder1450 I don't think so, I would guess there's some other little syntax error that's causing it. Oh, yeah I just saw it. I'll edit. I was accessing `HasValue` from `model` when there is one more layer of indirection. The error message isn't intuitive :| – evanmcdonnal Mar 05 '14 at 20:46