【发布时间】:2008-11-10 10:47:50
【问题描述】:
我有一个带有表单的 ASP.NET MVC 项目。在处理 POST 动词的 Action 方法中,我有一个自定义的 IModelBinder 实现,它将表单数据绑定到我的模型实例。如果有错误,我使用bindingContext.ModelState.SetAttemptedValue() 和bindingContext.ModelState.AddModelError() 将提交的值和错误消息保存到ModelState。
这很好用,我可以看到使用Html.TextBox()(调用Html.InputHelper())呈现的输入控件上发生的预期行为。当我使用Html.CheckBox()(也调用Html.InputHelper())时,我的复选框的状态是NOT输出到<input />标签。
在我看来,Html.InputHelper() 方法没有将 ModelState 中的 AttemptedValue 用于 CheckBox 类型的输入字段。
这是来自ASP.NET MVC Html.InputHelper() method的代码。
为什么CheckBox allowedValue 没有输出到输入标签。我这里有什么遗漏还是我需要通过检查 ModelState 并自己设置标签属性来手动处理这种情况?
2009 年 11 月更新
这是我用来输出 CheckBox 的对 HtmlHelpers 的调用:
<%= Html.CheckBox("IsDerived") %>
这是我用来注册尝试值的调用:
string isDerivedRequestValue = !string.IsNullOrEmpty(bindingContext.HttpContext.Request["IsDerived"]) ? bindingContext.HttpContext.Request.Form.GetValues("IsDerived") [0] : null;
bindingContext.ModelState.SetAttemptedValue("IsDerived", isDerivedRequestValue);
【问题讨论】:
标签: asp.net-mvc