【发布时间】:2018-02-03 00:55:23
【问题描述】:
我正在尝试使用 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”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或调用扩展方法而不使用扩展方法语法。
【问题讨论】:
-
你需要在
DropDownListFor()方法中强制转换——(IEnumerable<SelectListItem>)ViewBag.Brands -
理想情况下,您应该使用强类型视图模型。 stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc
标签: c# asp.net-mvc asp.net-mvc-4