MVC3 Razor @Html.DropDownListFor

26
我需要一些帮助来实现@Html.DropDownListFor。我的目标是通过类别筛选产品列表。 这段代码将显示一个列表框:
@model IEnumerable<Sample.Models.Product>
@{
    List<Sample.Models.Category> list = ViewBag.Categories;
    var items = new SelectList(list, "CategoryID", "CategoryName");

}
@Html.DropDownList("CategoryID", items)

但是我在使用@Html.DropDownListFor时遇到了问题:

@model IEnumerable<Sample.Models.Product>
@{
    List<Sample.Models.Category> list = ViewBag.Categories;
    var items = new SelectList(list, "CategoryID", "CategoryName");

}
@Html.DropDownListFor(???, @items)

我需要一些帮助来构建 @Html.DropDownListFor 的 Linq 部分。

以下是模型:

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int CategoryID { get; set; }
    public string QuantityPerUnit { get; set; }
    public Decimal? UnitPrice { get; set; }
    public short UnitsInStock { get; set; }

    public virtual Category Category { get; set; }
}

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    public virtual ICollection<Product> Products { get; set; }

}
3个回答

47

你的视图是针对产品集合进行强类型化的,因此我假设你需要为每个产品提供一个下拉列表。如果是这种情况,可以使用编辑器模板:

@model IEnumerable<Sample.Models.Product>
@Html.EditorForModel()

然后在 ~/Views/Shared/EditorTemplates/Product.cshtml 内部

@model Sample.Models.Product
@{
    List<Sample.Models.Category> list = ViewBag.Categories;
    var items = new SelectList(list, "CategoryID", "CategoryName");
}
@Html.DropDownListFor(x => x.CategoryID, @items)

太棒了,感谢你的解决方案Darin。是否可以选择两个属性作为SelectList的dataTextField,例如:List<_3iApp.Models.Person> list = ViewBag.People; var items = new SelectList(list, "ID", "Firstname, Surname"); - Jimmy

2

我的建议:

扩展您的LINQ数据上下文类,使用静态函数返回所有类别的SelectList,并使用Html.DropDownList()显示此列表。

然后,为此相同操作添加一个控制器,接受类别ID并返回对应于该类别的IEnumerable<Product>列表。


0

这里有另一种实现你想要的方法。

在模型中,我有两个条目。

  public class Product
  {
     public int CategoryID { get; set; }
     public IEnumerable<SelectListItem> Category { get; set; }
  }

然后我从数据库或静态地填充SelectlestItem。在Index.cs控制器中。

   product model = new product();

   model.Category = <whereever you generated the data>;

   return View(model);

在视图中

    @using (Html.BeginForm("Edit", "Subject", FormMethard.Post, new { id = "genform"}))
    {
       <div class="vertical-space spaced-field">@Html.DropDownListFor(m => m.CategoryID, model,Category)</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接