2014-05-15 31 views
0

我有一个@Html.DropDownListFor,它显示了我的数据库中的项目列表。如果未选择任何值,则Html.DropDownListFor会出错

非常简单的我与这些PARAMATERS一个ViewModel

public class RegisterViewModel 
{ 
    [Required] 
    [Display(Name = "Country")] 
    public string SelectedCountryId { get; set; } 
    public IEnumerable<System.Web.Mvc.SelectListItem> CountryList { get; set; } 

    [Required] 
    [Display(Name = "User name")] 
    public string UserName { get; set; } 
} 

我然后在我的控制器填充IEnumerable<System.Web.Mvc.SelectListItem>本:

IEnumerable<SelectListItem> countries = _DB.Countries.Where(x => x.Status == Status.Visible) 
         .Select(x => new SelectListItem() 
         { 
          Value = x.ID + "", 
          Text = "(+" +x.PhoneCountryCode + ") - " + x.Name 
         }).ToList(); 
    countries.First().Selected = true; 

我然后使用以下HTML显示选项集

@Html.DropDownListFor(m => m.SelectedCountryId, Model.CountryList, new { @class = "form-control" }) 

选项列表总是有第一个o选择页面加载时,如果你点击它有三个选项可供选择。

我的问题是,如果你不打开列表,然后选择一个项目(即只要把它的默认值),这个错误是从我的观点抛出,

具有的ViewData的项目键'SelectedCountryId'的类型为 'System.String',但必须是'IEnumerable'类型。

如果您打开下拉菜单并手动选择项目,则不会发生此错误。如果我从列表SelectedCountryId中选择一些其他项目确实得到正确的值。

我尝试将public string SelectedCountryId { get; set; }string改为IEnumerable<SelectListItem>,而这确实使错误消失,但列表始终为空。

任何好点子?

+0

http://stackoverflow.com/questions/7142961/mvc3-dropdownlistfor-a-simple-example –

回答

1

在你的控制器当模型是无效的,重新填充下拉列表:

if (ModelState.IsValid) 
{ 
IEnumerable<SelectListItem> countries = _DB.Countries.Where(x => x.Status == Status.Visible) 
        .Select(x => new SelectListItem() 
        { 
         Value = x.ID + "", 
         Text = "(+" +x.PhoneCountryCode + ") - " + x.Name 
        }).ToList(); 
countries.First().Selected = true; 
} 
else 
{ 
    //We need to rebuild the dropdown or we're in trouble 
    IEnumerable<SelectListItem> countries = _DB.Countries.Where(x => x.Status == Status.Visible) 
         .Select(x => new SelectListItem() 
         { 
          Value = x.ID + "", 
          Text = "(+" +x.PhoneCountryCode + ") - " + x.Name 
         }).ToList(); 
    countries.First().Selected = true; 
} 

您也可以使用此检查在模型状态中的错误。 可能有一些有趣的事情:

var errors = ModelState 
       .Where(x => x.Value.Errors.Count > 0) 
       .Select(x => new { x.Key, x.Value.Errors }) 
       .ToArray(); 
+0

这不是问题,但使我的问题是什么。真正的问题是'ModelState.IsValid == false',这是由另一个不相关的定制属性引起的,我通过查看'ModelState'中的错误列表来解决这个问题。仍然奇怪,该错误显示在DropDownFor字段..感谢您的帮助! – JensB

+0

欢迎,因为我带你到解决方案,我可以获得批准的答案? ;) – meda

相关问题