到 DropDownListFor 的强类型绑定? [英] Strongly-typed binding to a DropDownListFor?

查看:21
本文介绍了到 DropDownListFor 的强类型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我会将数据绑定到带有 SelectListDropDownListFor:

Normally I would bind data to a DropDownListFor with a SelectList:

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

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

Is there any way to do this through strongly-typed lambdas and not with property strings. For example:

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

推荐答案

您可以在控制器中创建选择列表本身,并将其分配给视图模型中的属性:

You could create the select list itself in the controller and assign it to a property in your view model:

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

控制器中的代码如下所示:

The code in your controller will look like this:

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

在视图中你可以这样使用它:

In the view you can use it like this:

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

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

I personally prefer this approach since it reduces logic in your views. It also keeps your logic 'stronly-typed', no magic strings anywhere.

这篇关于到 DropDownListFor 的强类型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆