我有一个@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>
,而这确实使错误消失,但列表始终为空。
任何好点子?
http://stackoverflow.com/questions/7142961/mvc3-dropdownlistfor-a-simple-example –