linq - MVC3 Razor @Html.DropDownListFor

标签 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; }

}

最佳答案

您的 View 是强类型的产品集合,因此我想您需要为每个产品提供一个下拉列表。如果是这种情况,编辑器模板将起作用:

@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)

关于linq - MVC3 Razor @Html.DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5070762/

相关文章:

c# - Linq Func 委托(delegate) - 可以添加到吗?

c# - 如何使用 AutoMapper 3 和 Entity Framework 将整数映射到字符串

c# - MVC3 HttpStatusCodeResult 在 OnActionExecuted 中不起作用

C# MVC 处理 View 中的编译错误,例如缺少装配引用?

c# - 在单个 Razor View 中,如何检索从 Controller 的不同方法传递的值?

javascript - jQuery 像 Linq 一样?

c# - 使用 Linq 计算父对象

asp.net - 如何使用 ? : if statements with Razor and inline code blocks

asp.net-mvc - OutputCache 停止工作

asp.net - 来自 Microsoft.AspNet.WebApi.HelpPage 版本 4.0.30506 的运行时编译错误