gpt4 book ai didi

c# - 强类型绑定(bind)到 DropDownListFor?

转载 作者:太空狗 更新时间:2023-10-29 20:02:56 25 4
gpt4 key购买 nike

通常我会使用 SelectList 将数据绑定(bind)到 DropDownListFor:

@Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Orders, "OrderId", "ItemName"))

有没有办法通过强类型的 lambda 而不是使用属性字符串来做到这一点。例如:

@Html.DropDownListFor(model => model.CustomerId, new SelectList(Model.Orders, x => x.OrderId, x => x.ItemName))

最佳答案

您可以在 Controller 中创建选择列表本身并将其分配给 View 模型中的属性:

public IEnumerable<SelectListItem> OrdersList { get; set; }

Controller 中的代码如下所示:

model.OrdersList = db.Orders
.Select(o => new SelectListItem { Value = o.OrderId, Text = o.ItemName })
.ToList();

在 View 中你可以这样使用它:

@Html.DropDownListFor(model => model.CustomerId, Model.OrderList)

我个人更喜欢这种方法,因为它减少了您 View 中的逻辑。它还使您的逻辑保持“强类型”,任何地方都没有魔法字符串。

关于c# - 强类型绑定(bind)到 DropDownListFor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20419957/

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