How to create an optional yes / no radiobutton in your viewmodel

亡梦爱人 提交于 2019-12-08 14:43:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!