2014-05-15 40 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

相關問題