gpt4 book ai didi

linq - MVC3 Razor @Html.DropDownListFor

转载 作者:行者123 更新时间:2023-12-03 10:22:51 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com