我正在尝试使用DropDownListFor向我的视图添加一个下拉列表,我不确定我做错了什么。
我的模特:
public class Catalog
{
public Catalog()
{
this.Locations = new HashSet<Location>();
this.Categories = new HashSet<Category>();
this.SubCategories = new HashSet<SubCategory>();
}
[Key]
public int CatalogID { get; set; }
public int BrandID { get; set; }
public int WarrantyPDFID { get; set; }
public string Name { get; set; }
public string PDF { get; set; }
public bool Active { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public int ModifiedBy { get; set; }
public bool SoftDelete { get; set; }
public virtual ICollection<Location> Locations { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<SubCategory> SubCategories { get; set; }
public virtual Brand Brand { get; set; }
public virtual WarrantyPDF WarrantyPDF { get; set; }
}
public class Brand
{
[Key]
public int BrandID { get; set; }
public string Name { get; set; }
public int Sort { get; set; }
public bool Active { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public int ModifiedBy { get; set; }
public bool SoftDelete { get; set; }
}
控制器添加功能(HttpGet)
public ActionResult AddCatalog()
{
Context _db = new Context();
Catalog catalog = new Catalog();
List<SelectListItem> brands = new List<SelectListItem>();
foreach(var brand in _db.Brands)
{
var item = new SelectListItem
{
Value = brand.BrandID.ToString(),
Text = brand.Name
};
brands.Add(item);
}
ViewBag.Brands = brands;
return View(catalog);
}
我的观点的相关部分
@model App.Models.Catalog
@{
ViewBag.Title = "AddCatalog";
Layout = "~/Views/LayoutAdmin.cshtml";
}
<h2>Add Catalog</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Catalog</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
Brand
<div class="col-md-10">
@Html.DropDownListFor(m => m.BrandID, ViewBag.Brands, "Select Brand", null)
@Html.ValidationMessageFor(model => model.BrandID, "", new { @class = "text-danger" })
</div>
</div>
当我尝试加载页面时,我收到此错误。 编译器错误消息:CS1973:'System.Web.Mvc.HtmlHelper'没有名为'DropDownListFor'的适用方法,但似乎有一个名称的扩展方法。无法动态分派扩展方法。考虑转换动态参数或调用扩展方法而不使用扩展方法语法。
答案 0 :(得分:0)
表达式ViewBag.Brands
的类型为dynamic
。您正在使用的DropDownListFor
辅助方法的重载需要SelectListItem
的集合作为第二个参数。因此,您需要将存储在ViewBag.Brands
中的数据转换为SelectListItems
这应该有用。
@Html.DropDownListFor(m => m.BrandID, (IEnumerable<SelectListItem>)ViewBag.Brands ,
"Select Brand", null)
或使用as
安全投射操作员
@Html.DropDownListFor(m => m.BrandID, ViewBag.Brands as IEnumerable<SelectListItem>,
"Select Brand", null)