MVC3 Razor @Html.DropDownListFor [英] MVC3 Razor @Html.DropDownListFor
问题描述
我可以使用一些帮助来实现@Html.DropDownListFor.我的目标是按类别过滤产品列表.
I could use some help implementing @Html.DropDownListFor. My objective is to filter the list of Products by Category.
此代码将显示一个列表框:
This code will display a list box:
@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
工作:
But I'm having trouble getting @Html.DropDownListFor
to work:
@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 部分.这是模型:
I could use some help constructing the Linq portion of @Html.DropDownListFor
.
Here is the model:
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; }
}
推荐答案
您的视图是强类型的产品集合,因此我想您需要为每个产品设置一个下拉列表.如果是这种情况,编辑器模板将起作用:
Your view is strongly typed to a collection of products so I suppose that you need a drop down for each product. If this is the case an editor template would work:
@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)
这篇关于MVC3 Razor @Html.DropDownListFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!