[英]Allow Nullable<bool> in ASP.NET MVC form on submission
I have a model with some properties being of type Nullable. 我有一个模型,其中某些属性为Nullable类型。
public Nullable<bool> Continuing { get; set; }
public Nullable<bool> Incomplete { get; set; }
//..etc other properties omitted for brevity
I have successfully bound this in a form with 3 radio buttons but when I submit the form, ModelState.IsValid
returns false. 我已经成功地将它绑定到具有3个单选按钮的表单中,但是当我提交表单时,
ModelState.IsValid
返回false。
The controller: 控制器:
[HttpPost]
public ActionResult CreateSub(MyModel model)
{
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
I had a look at the errors and it is saying that the value 'null'
is not allowed for the properties of type Nullable<bool>
- I don't seem to understand why. 我看了一下错误,这是说
Nullable<bool>
类型的属性不允许使用值'null'
Nullable<bool>
我似乎不明白为什么。
the error: 错误:
EDIT: 编辑:
This is how I am binding the properties to the radios: 这就是我将属性绑定到收音机的方式:
<div class="btn-group" data-toggle="buttons">
@Html.RadioButtonFor(x => x.Continuing, true, new {@class = "Continuing-true", style="visibility: hidden; margin-left:-13px"})
<label class="btn-cohort btn btn-sm btn-default @if(Model.Continuing.HasValue && Model.Continuing.Value) { <text>btn-custom-green active</text> } " data-value="true">
<input type="radio" name="options" value="true" />
T
</label>
@if(!Model.Continuing.HasValue) {
@Html.RadioButtonFor(x => x.Continuing, "null", new {@checked = "checked", @class = "Continuing-null", style="visibility: hidden; margin-left:-13px"})
} else {
@Html.RadioButtonFor(x => x.Continuing, "null", new {@class = "Continuing-null", style="visibility: hidden; margin-left:-13px"})
}
<label class="btn-cohort btn btn-sm btn-default btn-n @if(!Model.Continuing.HasValue) { <text>active</text> } " data-value="null">
<input type="radio" name="options" value="null"/>
N
</label>
@Html.RadioButtonFor(x => x.Continuing, false, new {@class = "Continuing-false", style="visibility: hidden; margin-left:-13px"})
<label class="btn-cohort btn btn-sm btn-default @if(Model.Continuing.HasValue && !Model.Continuing.Value) { <text>btn-custom-red active</text> } " data-value="false">
<input type="radio" name="options" value="false" />
F
</label>
</div>
Change your Html helper usage to 将您的HTML帮助器用法更改为
@Html.RadioButtonFor(x => x.Continuing, "", ...)
and the manual html to 和手册的HTML
<input ... value="" />
so they posts back and empty string as opposed to a string
with the value "null"
which the ValueProviders
cannot convert to null
所以他们回发和,而不是一个空字符串
string
,其值为"null"
该ValueProviders
不能转换为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.