MVC SelectList在文本字段中组合多个列

Mar*_*ark 50 asp.net asp.net-mvc razor asp.net-mvc-3

如何生成一个选择列表,其中文本字段由两个或多个文本列组成,例如:我在数据库中有一个描述和速率字段,我想将这些组合显示:

Large--£200
Medium--£150
Small--£100
Run Code Online (Sandbox Code Playgroud)

控制器代码是:

 var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
 ViewBag.StandID = new SelectList(stands,"StandID", "Description" + "-- £" + "Rate");
Run Code Online (Sandbox Code Playgroud)

......我的观点是(目前):

    <div class="editor-field"> 
        @Html.DropDownList("StandID", "--Select--") 
    </div> 
Run Code Online (Sandbox Code Playgroud)

...但是"描述"+" - £"+"费率"); 不会运行:

DataBinding:'System.Data.Entity.DynamicProxies.Stand_63F8C9F623B3C0E57D3008A57081AFCD9C39E1A6B79B0380B60840F1EFAE9DB4'不包含名称为'Description--£Rate'的属性.

谢谢你的帮助,

标记

Stu*_*tLC 79

您可以使用简单的LINQ投影创建一个新的匿名类,然后使用SelectList(IEnumerable, string, string) 构造函数重载来指定要用于<option>元素的值和文本字段,即:

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")
Run Code Online (Sandbox Code Playgroud)

编辑

在C#6及更高版本中,字符串插值比读取更好string.Format

   ...
   Description = $"{s.Description}-- £{s.Rate}"
Run Code Online (Sandbox Code Playgroud)

如果你投射到一个强大的ViewModel类名(而不是一个匿名类),你无疑会想要用nameof操作符的安全性替换魔术字符串:

ViewBag.StandID = new SelectList(stands, nameof(Stand.StandID), nameof(Stand.Description));
Run Code Online (Sandbox Code Playgroud)


chr*_*dam 14

var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
IEnumerable<SelectListItem> selectList = from s in stands
                                         select new SelectListItem
                                                    {
                                                      Value = s.StandID,
                                                      Text = s.Description + "-- £" + s.Rate.ToString()
                                                    };
ViewBag.StandID = new SelectList(selectList, "Value", "Text");
Run Code Online (Sandbox Code Playgroud)


Gui*_*ish 7

您可以创建部分Model类

public partial class Stand
{
    public string DisplayName
    {
        get
        {
            return this.Description + "-- £" + this.Rate.ToString();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在你的视图中

var stands = db.Stands.Where(s => s.ExhibitorID == null).ToList();
ViewBag.StandID = new SelectList(stands,"StandID", "DisplayName");
Run Code Online (Sandbox Code Playgroud)