只需要另一双眼睛。错误是:
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 :(得分: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; }
确保在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();
}
这应该有效
答案 1 :(得分:1)
请关注我的技巧。
<强>控制器强>
ViewBag.BrandForDropDown = Repository.GetBrandsForDropDown();
<强> HTML 强>
@Html.DropDownListFor(x => x.BrandId, ViewBag.BrandForDropDown as
List<SelectListItem>, "- Brand -")
谢谢。