MVC3 Razor @ Html.DropDownListFor

时间:2011-02-21 20:12:49

标签: linq asp.net-mvc-3 razor

我可以使用一些帮助来实现@ 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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

我的建议:

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

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

答案 2 :(得分: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>