2016-11-04 58 views
0

只需要另一組眼睛。錯誤是:MVC DropDownListFor發行密鑰

The ViewData item that has the key 'BrandId' is of type 'System.Int32' 
but must be of type IEnumerable<SelectListItem>. 

HTML

@Html.DropDownListFor(x => x.BrandId, Model.BrandForDropDown, "- Brand -") 

控制器

model.BrandForDropDown = Repository.GetBrandsForDropDown(); 

public SelectList GetBrandsForDropDown() 
    { 
     if (Membership.GetUser() != null) 
     { 
      return new SelectList((from store in DataContext.Stores 
          join userstore in DataContext.UserStores on store.StoreId equals userstore.StoreId 
          join brand in DataContext.Brands on store.BrandID equals brand.BrandID 
          where userstore.UserId == userId 
          select new SelectListItem 
          { 
           Value = brand.BrandID.ToString(), 
           Text = brand.BrandName 
          }).OrderBy(x => x.Text)); 
     } 

     return new SelectList(new List<Brand>()); 
    } 

型號

public int BrandId { get; set; } 
public SelectList BrandForDropDown { get; set; } 
..others omitted 

我也試過List<SelectListItem>以及在模型和視圖等,相同的錯誤

+0

回覆後,您返回相同的視圖後發生錯誤嗎? – Izzy

+0

@Izzy不,這是初始視圖加載 –

+0

如果你的'SelectList'沒有數據,也會出現同樣的錯誤信息 – Izzy

回答

1

您的代碼有一個問題。創建選擇列表時,您需要指定dataValueField和dataTextField。所以無論你在服務器方法還是在視圖中使用它,都必須這樣做。

這是你如何做,在你的方法

select new SelectListItem 
         { 
         Value = brand.BrandID.ToString(), 
         Text = brand.BrandName 
         }).OrderBy(x => x.Text),"Value","Text"); 

另一種選擇是簡單地將屬性類型更改爲List<SelectListItem>和更新方法返回類型。

public int BrandId { get; set; } 
public List<SelectListItem> BrandForDropDown { get; set; } 

確保您返還相同種類,當你如果條件不滿足

public List<SelectListItem>GetBrandsForDropDown() 
{ 
    if(Membership.GetUser() != null) 
    { 
    // your existing code 
       select new SelectListItem 
       { 
         Value = brand.BrandID.ToString(), 
         Text = brand.BrandName 
       }).OrderBy(x => x.Text)); 
    } 
    return new List<SelectListItem(); 
} 

這應該工作

1

請按照我的絕招。

控制器

ViewBag.BrandForDropDown = Repository.GetBrandsForDropDown(); 

HTML

@Html.DropDownListFor(x => x.BrandId, ViewBag.BrandForDropDown as 
List<SelectListItem>, "- Brand -") 

感謝。