MVC DropDownListFor Issue w/ key

本文关键字:key Issue DropDownListFor MVC | 更新日期: 2023-09-27 18:16:32

只是需要另一双眼睛。错误:

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>以及在模型和视图等,同样的错误

MVC DropDownListFor Issue w/ key

你的代码有一个问题。您需要在创建选择列表时指定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; }

确保在if条件失败时返回相同的类型

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();
}

应该可以

请跟随我的魔术。

控制器

ViewBag.BrandForDropDown = Repository.GetBrandsForDropDown();

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

谢谢。