ASP.NET MVC:DropDownList的验证 [英] ASP.NET MVC: DropDownList validation
问题描述
注:以下仅仅是一个例子。
我是pretty新的ASP.NET MVC和我试图让我周围的下拉列表的验证是如何工作的负责人。我有以下属性我 ProfileViewModel
类:
[DisplayName的(性别)]
公共BOOL?性别{搞定;组; }
空
是为了表示未知,真正
女性和假
男性。在视图模型构造I
AllGenders =新的List< SelectListItem>(2)
{
新SelectListItem的{text =未知,值=空},
新SelectListItem的{text =男,值=假},
新SelectListItem的{text =女,值=真}
};
首先,看来我有填充列表与LT时使用的字符串; SelectListItem>
,感觉有点怪怪的。这真的是它是如何做的?
其次,当我在列表中选择未知验证失败告诉我:
'空'的值不是有效的性别。块引用>这是为什么?当我删除了空选项,并更改
性别
来一个简单的布尔
,一切似乎都很好。这是ASPX:
<%= Html.DropDownList(性别,Model.AllGenders)%GT;
(我不能让
DropDownListFor
正常工作,似乎很多人有同样的问题。)任何帮助AP preciated!
解决方案新SelectListItem的{text =未知,值=空},
应该是:
新SelectListItem的{text =未知,值=},
发布,将导致空的限制。
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 andfalse
male. In the view model constructor IAllGenders = 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 simplebool
, 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!
解决方案new SelectListItem {Text = "Unknown", Value = "null"},
should be:
new SelectListItem {Text = "Unknown", Value = ""},
Posting "" will result in null being bound.
这篇关于ASP.NET MVC:DropDownList的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!