ASP.NET MVC:DropDownList 验证
注意:以下只是一个示例。
我对 ASP.NET MVC 还很陌生,我正在尝试了解下拉列表验证的工作原理。我的 ProfileViewModel
类中有以下属性:
[DisplayName("Gender")]
public bool? Gender { get; set; }
null
表示“未知”,true
女性,false
> 男性。在视图模型构造函数中
AllGenders = new List<SelectListItem>(2)
{
new SelectListItem {Text = "Unknown", Value = "null"},
new SelectListItem {Text = "Male", Value = "false"},
new SelectListItem {Text = "Female", Value = "true"}
};
,我首先似乎在填充 List
时必须使用字符串,这感觉有点奇怪。真的是这样的吗?
其次,当我在列表中选择“未知”时,验证失败,告诉我:
值“null”对于性别无效。
这是为什么?当我删除“null”选项并将 Gender
更改为简单的 bool
时,一切看起来都很好。
这是 ASPX:(
<%= Html.DropDownList("Gender", Model.AllGenders) %>
我无法让 DropDownListFor
正常工作,似乎许多其他人也有同样的问题。)
任何帮助表示赞赏!
Note: The following is just an example.
I'm pretty new to ASP.NET MVC and I'm trying to get my head around how validation of dropdown lists work. I have the following property in my ProfileViewModel
class:
[DisplayName("Gender")]
public bool? Gender { get; set; }
null
is meant to mean "unknown", true
female and false
male. In the view model constructor I
AllGenders = new List<SelectListItem>(2)
{
new SelectListItem {Text = "Unknown", Value = "null"},
new SelectListItem {Text = "Male", Value = "false"},
new SelectListItem {Text = "Female", Value = "true"}
};
First of all, it seems that I have to use strings when populating a List<SelectListItem>
, which feels kinda weird. Is this really how it's done?
Secondly, when I choose "Unknown" in the list the validation fails telling me:
The value 'null' is not valid for Gender.
Why is that? When I remove the "null" option and change Gender
to a simple bool
, everything seems fine.
This is the ASPX:
<%= Html.DropDownList("Gender", Model.AllGenders) %>
(I can't get DropDownListFor
to work correctly and it seems that many others have the same problem.)
Any help appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
应该是:
发布“”将导致空值被绑定。
should be:
Posting "" will result in null being bound.