0

I am trying to create a CheckBox in MVC using Razor and here is the Below code for it :

@Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet, new { @class = "marksheet" })

But it is showing error Cannot implicitly convert 'bool?' to 'bool'. Are you missing the type cast. To Solve this i have used @Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet.Value, new { @class = "marksheet" }) and it is giving this error : Nullable object must have a value.

and @Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet.GetValueOrDefault(), new { @class = "marksheet" }) and it is giving this error : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Any Suggestion will be thankful.

Thanks in Adavance

1
  • You should change your field to bool. There is no sense to have chechbox value which can be null. Commented Oct 25, 2014 at 8:37

1 Answer 1

1

You cannot create a checkbox for a nullable bool. A check box has 2 states, checked/true and unchecked/false, but a nullable bool has 3 states, true, false and null so its not possible to post back a value indicating if its false or null.

You can use

@Html.EditorFor(m => m.PDModel.EducationMasterList[0].eduMarksheet, ...

which will render a dropdown list containing 3 values ("True", "False" and "Not set"). Another option is to create 3 radio buttons.

Note that @Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet.Value, ..) would be pointless since it creates a checkbox and associated hidden input with the attribute name="EducationMasterList[0].eduMarksheet.Value" so when it posted back it would not match any model property and binding would fail.

Sign up to request clarification or add additional context in comments.

5 Comments

Only if you make your property bool, not bool?
I can't make that feild bool? to bool because if user has not checked it , it should enter null value in that feild. Thats why i have made that feild Nullable
In that case you need @Html.EditorFor() or 3 radio buttons (for "true, "false" and "not set") as I indicated in my answer. But if the user has not checked it why cant that mean "false" instead of "null". A nullable bool is only required when you need 3 possible values for example - YES or NO or I DONT KNOW
Then change the property to bool. You cant do the impossible.
Then perhaps you should consider accepting the answer to close this out

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.