ASP.NET MVC:DropDownList 验证

发布于 2024-09-17 05:13:42 字数 1043 浏览 14 评论 0原文

注意:以下只是一个示例。

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慈悲佛祖 2024-09-24 05:13:42
new SelectListItem {Text = "Unknown", Value = "null"},

应该是:

new SelectListItem {Text = "Unknown", Value = ""},

发布“”将导致空值被绑定。

new SelectListItem {Text = "Unknown", Value = "null"},

should be:

new SelectListItem {Text = "Unknown", Value = ""},

Posting "" will result in null being bound.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文