问题
Say I have long form, with many different optional values a user can enter.
One of these optional values is a boolean. Depending on the user input, I need to do the following in my database:
- If "yes", then add "1" in the database
- If "no", then add "0" in the database
- If non is entered, add "null" in the database
However, the most normal viewmodel / razor code I could find is the following:
@Html.LabelFor(m => m.FurnitureIsIncluded)
@Html.RadioButtonFor(model => model.FurnitureIsIncluded, true) Ja
Here my value would be false, as the default value of a boolean.
What is the way to fix this in MVC?
回答1:
Use a nullable bool for FurnitureIsIncluded
in your view model
@Html.RadioButtonFor(m => m.FurnitureIsIncluded, "true")<span>Yes</span>
@Html.RadioButtonFor(m => m.FurnitureIsIncluded, "false")<span>No</span>
@Html.RadioButtonFor(m => m.FurnitureIsIncluded, "", Model.FurnitureIsIncluded.HasValue ? null : new { @checked = "checked" })<span>Cant decide</span>
This will then post back true
or false
or null
based on the selection. You would then need need to test for true/false to save the value as "1" or "0"
来源:https://stackoverflow.com/questions/25659027/how-to-create-an-optional-yes-no-radiobutton-in-your-viewmodel