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; }
1

2 Answers 2

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();"}) 
}
Sign up to request clarification or add additional context in comments.

9 Comments

System.Nullable <bool> does not contain definition for GetValueOfDefault
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
I've used GetValueOrDefault(false)
Can you show the complete line of code you have in your view?
@Html.CheckBoxFor(model => model.VisitRequested.GetValueOrDefault(false), new { onClick = "showHide();" })
|
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.

2 Comments

model does not exist in the current context. Do I have to use @{} symbols for the code?
@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 :|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.