【发布时间】:2017-08-14 21:14:05
【问题描述】:
有没有比我在下面的视图中使用SelectList 的Value 和Text 属性更好的方法?我觉得我做了一些超出应有的工作。
注意:我知道在Value 和Text 中使用下拉菜单的其他方式。这个问题仅与使用SelectList时如何实现相同的目的有关
...
var customersList = _context.Customers.Select(c => new SelectListItem { Value = c.LastName, Text = c.FullName });
MyViewModel.lstCustomers = new SelectList(customersList , "Value", "Text");
...
return View(MyViewModel);
【问题讨论】:
-
customersList已经是IEnumerable<SelectListItem>。使用new SelectList(...)创建另一个相同的IEnumerable<SelectListItem>只是毫无意义的额外开销。您的lstCustomers属性应该是IEnumerable<SelectListItem>,因为这就是您视图中DropDownListFor()方法所需要的全部内容。 -
@StephenMuecke 这就是我担心的——做不必要的额外工作。如果我要使用
SelectList,我应该如何使用Value和Text属性? -
你没看懂我的评论吗?它使用新的
SelectList()毫无意义。要生成<select>,您需要一个IEnumerable<SelectLitsItem>属性-您已经拥有它-这就是您的var customersList = ...代码所做的。SelectList是IEnumerable<SelectListItem>和你的代码的第二行只是创建另一个相同的。 -
你不能使用
new SelectList(...)来处理复杂对象的集合,除非你没有指定第二个和第三个参数——它只会生成所有<option>System.MVC.SelectListItem</option>,因为如果你省略第二个和第三个参数它使用集合中对象的.ToString()来生成选项显示文本 -
你要么做
MyViewModel.lstCustomers = _context.Customers.Select(c => new SelectListItem { Value = c.LastName, Text = c.FullName });要么你做MyViewModel.lstCustomers = new SelectList(_context.Customers, "LastName", "FullName");不是两者都
标签: c# linq asp.net-core selectlist