asp.net mvc 中的空下拉列表验证
我有一个页面,上面有 2 个表格。其中一个有一个下拉列表:
<form ...>
<%: Html.DropDownListFor(x => Model.NewForm.FormId, Model.Forms)%>
<%: Html.ValidationMessageFor(x => Model.NewForm.FormId, "*")%>
<input type="submit" value="Add" />
</form>
模型的 NewForm 属性是:
public class AddFormViewModel
{
[Required]
[DisplayName("Form Id:")]
public int? FormId { get; set; }
}
我注意到,当下拉列表为空时,“form”参数始终为 null,并且 ModelState 始终有效。
[HttpPost]
public ActionResult AddForm([Bind(Prefix="NewForm")]AddFormViewModel form)
{
if (ModelState.IsValid)
{
... save
}
else
{
... show validation error
}
return ...
}
当下拉列表不为空时,一切都会按预期工作,“form”不为空。
下拉列表的值在为空时不会发送,这是默认行为,但无论如何,如何使验证工作?
一些想法:
1)我可以添加一个属性来查看模型,这将是页面上的隐藏输入,只是为了使模型绑定器工作;
2) 定制模型活页夹
你的想法是什么?
I have a page with 2 forms on it. One of them has a drop-down list on it:
<form ...>
<%: Html.DropDownListFor(x => Model.NewForm.FormId, Model.Forms)%>
<%: Html.ValidationMessageFor(x => Model.NewForm.FormId, "*")%>
<input type="submit" value="Add" />
</form>
The Model's NewForm property is:
public class AddFormViewModel
{
[Required]
[DisplayName("Form Id:")]
public int? FormId { get; set; }
}
I've noticed that when the drop-down list is empty, the 'form' argument is always null and ModelState is always valid.
[HttpPost]
public ActionResult AddForm([Bind(Prefix="NewForm")]AddFormViewModel form)
{
if (ModelState.IsValid)
{
... save
}
else
{
... show validation error
}
return ...
}
When drop-down list is not empty, everything works as expected, 'form' is not null.
Drop-down list's value is not send when it is empty, this is the default behavior, but anyway, how to make validation work?
Some ideas:
1) I can add a property to view model which will be a hidden input on page just to make model binder work;
2) Custom model binder
What are your ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样
How about