MVC SelectList在文本字段中组合多列 [英] MVC SelectList combining multiple columns in text field
问题描述
我将如何生成一个选择列表,其中文本字段由两个或多个文本列组成,例如:如果我的数据库中有一个描述和速率字段,我想将它们组合起来显示:>
大--£200中等--£150小——100英镑
控制器代码为:
var stand = db.Stands.Where(s => s.ExhibitorID == null).ToList();ViewBag.StandID = new SelectList(stands,"StandID", "Description" + "-- £" + "Rate");
...我的观点是(目前):
@Html.DropDownList("StandID", "--Select--")
...但是描述"+--£"+价格");不会运行:
<块引用>数据绑定:'System.Data.Entity.DynamicProxies.Stand_63F8C9F623B3C0E57D3008A57081AFCD9C39E1A6B79B0380B60840F1EFAE9DB4'不包含名为Description--£Rate"的属性.
感谢您的帮助,
标记
您可以使用简单的 LINQ 投影创建一个新的匿名类,然后使用 SelectList(IEnumerable, string, string)
构造函数重载 用于指定值和文本字段用于 元素,即:
var 代表 =db.stands.Where(s => s.ExhibitorID == null).Select(s => new{StandID = s.StandID,Description = string.Format("{0}-- £{1}", s.Description, s.Rate)}).ToList();ViewBag.StandID = new SelectList(stands, "StandID", "Description")
编辑
在 C#6 及更高版本中,字符串插值使得效果更好阅读比string.Format
<代码> ...描述 = $"{s.Description}-- £{s.Rate}"
如果你投射到一个强 ViewModel
类名(而不是一个匿名类),你无疑会想用 nameof
运营商:
ViewBag.StandID = new SelectList(stands, nameof(Stand.StandID), nameof(Stand.Description));
How would I generate a select list, where the text field, is made up of two or more text columns, eg: Where I have a Description and Rate field in my database, I want to combine these to show:
Large--£200
Medium--£150
Small--£100
Controller code is:
var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
ViewBag.StandID = new SelectList(stands,"StandID", "Description" + "-- £" + "Rate");
...and my view is (currently):
<div class="editor-field">
@Html.DropDownList("StandID", "--Select--")
</div>
...but the "Description" + "-- £" + "Rate"); won't run:
DataBinding: 'System.Data.Entity.DynamicProxies.Stand_63F8C9F623B3C0E57D3008A57081AFCD9C39E1A6B79B0380B60840F1EFAE9DB4' does not contain a property with the name 'Description--£Rate'.
Thanks for any help,
Mark
You could create a new anonymous class using a simple LINQ projection, and then use the SelectList(IEnumerable, string, string)
constructor overload to specify the value and text fields to be used for the <option>
elements i.e.:
var stands =
db.Stands
.Where(s => s.ExhibitorID == null)
.Select(s => new
{
StandID = s.StandID,
Description = string.Format("{0}-- £{1}", s.Description, s.Rate)
})
.ToList();
ViewBag.StandID = new SelectList(stands, "StandID", "Description")
Edit
In C#6 and later, string interpolation makes for better reading than string.Format
...
Description = $"{s.Description}-- £{s.Rate}"
If you project to a strong ViewModel
class name (instead of to an anonymous class), you will undoubtedly want to replace the magic strings with the safety of the nameof
operator:
ViewBag.StandID = new SelectList(stands, nameof(Stand.StandID), nameof(Stand.Description));
这篇关于MVC SelectList在文本字段中组合多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!