2010-05-16 80 views
1

我在DropDownList中强型模型视图类ASP.NET MVC的DropDownList验证

[DisplayName("Country")] 
public List<SelectListItem> Countries { get; set; } 

财产。

当我尝试检查ModelState.IsValid的形式回发,它总是假&错误国家告诉“无法转换[值]以SelectListItem”或某种一种。

我觉得没有下拉选择值的直接映射(看起来像我必须从表单值集合中读取值),但我怎样才能忽略List属性的绑定和验证?我只是想让ModelState.IsValid属性为true,如果所有其他字段正确填充。

预先感谢您

回答

0

是因为提交的值是String类型或Country的,而不是SelectListItemList<SelectListItem>列表。

你在UI中绑定了什么控件?

尝试

[DisplayName("Country")] 
public List<Country> Countries { get; set; } 

哪里Country是从你的DAL类型名称。

编辑: 根据您recieving错误,这听起来像模型期待值是一个String所以尝试换List<Country>List<String>

[DisplayName("Country")] 
public List<string> Countries { get; set; } 
+1

仍然是一样的ModelState错误。无法从字符串转换到国家 – 2010-05-16 18:37:50

+0

所以它需要是一个String然后。告诉你你是什么 需要做。 – 2010-05-17 08:45:38

+0

但它不能是一个字符串,因为它是一些东西:) 我放弃了我的尝试使用DropDownListFor并使用DropDownList与[name]属性指向视图模型中的字符串属性 – 2010-05-17 09:10:55

0

最后我用了解决方法。

我现在型号:

class Model 
{ 
... 
    [DisplayName("Country")] 
    List<Country> Countries; 

    Guid CountrySelected <-- new field! 
... 
} 

我用Html.DropDownList( “CountrySelected”,Model.Countries.Select(X =>新SelectItemList ..)

代替HtmlDropDownListFor HtmlDropDownListFor地图[ id selected]列表为不是CountrySelected属性现在[id selected]映射到CountrySelected