【问题标题】:How to use Display Text property in SelectList如何在 SelectList 中使用 Display Text 属性
【发布时间】:2017-08-14 21:14:05
【问题描述】:

有没有比我在下面的视图中使用SelectListValueText 属性更好的方法?我觉得我做了一些超出应有的工作。

注意:我知道在ValueText 中使用下拉菜单的其他方式。这个问题仅与使用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);

我发现herehere有类似的方法。

【问题讨论】:

  • customersList 已经是IEnumerable<SelectListItem>。使用new SelectList(...) 创建另一个相同的IEnumerable<SelectListItem> 只是毫无意义的额外开销。您的lstCustomers 属性应该是IEnumerable<SelectListItem>,因为这就是您视图中DropDownListFor() 方法所需要的全部内容。
  • @StephenMuecke 这就是我担心的——做不必要的额外工作。如果我要使用SelectList,我应该如何使用ValueText属性?
  • 你没看懂我的评论吗?它使用新的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


【解决方案1】:

用于生成<select> 元素(@Html.DropDownListFor() 等)的HtmlHelper 方法期望IEnumerable<SelectListItem> 作为参数之一,因此您的lstCustomers 也应该是IEnumerable<SelectListItem>

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

你的第一行代码

var customersList = _context.Customers.Select(c => new SelectListItem { Value = c.LastName, Text = c.FullName });

已经生成了,所以只需要

MyViewModel.lstCustomers = customersList;

您使用new SelectList(customersList , "Value", "Text"); 只是从第一个IEnumerable&lt;SelectListItem&gt; 创建另一个相同的IEnumerable&lt;SelectListItem&gt;,并且是不必要的额外开销。 (SelectList IEnumerable&lt;SelectListItem&gt; 只是一个包装器,提供构造函数来生成集合)。

如果您想使用SelectList 构造函数,请将您的代码更改为

var customersList = _context.Customers;
MyViewModel.lstCustomers = new SelectList(customersList , "LastName", "FullName");

两者都会产生相同的输出。方法之间的区别在于SelectList 构造函数使用反射来确定用于选项值和显示文本的属性,因此速度稍慢,并且它使用“魔术字符串”,因此不是强类型。好处是它不那么冗长。

【讨论】:

  • 我决定使用你的最后一个例子;虽然速度稍慢 - 我喜欢它不那么冗长。感谢您提供的详细信息,就像我自己一样,它也应该使其他读者受益。
  • 是的,这真的取决于个人喜好
猜你喜欢
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多