如何创建可选是/否单选按钮在你的视图模型 [英] How to create an optional yes / no radiobutton in your viewmodel

查看:143
本文介绍了如何创建可选是/否单选按钮在你的视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有长形,有许多不同的可选值,用户可以输入。

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:


  • 如果是,然后在数据库中添加1

  • 如果否,然后在数据库中添加0

  • 如果输入不,在数据库中添加空

然而,最正常的视图​​模型/剃须刀code,我能找到如下:

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.

什么是MVC解决这个问题的方法是什么?

What is the way to fix this in MVC?

推荐答案

在您的视图模型使用 FurnitureIsIncluded 可为空的布尔

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>

这会再回来后真正基于选择。那么你就需要需要测试真/假的值保存为1或0

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"

这篇关于如何创建可选是/否单选按钮在你的视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆