我正在从事ASP.NET MVC项目。
我已经能够将两个字段从表格组合到下拉列表中。但是,在创建和索引视图中,我都得到了这些" {}"括号,我不知道如何摆脱它们。
控制器://get:/create
var units = db.EquipmentLists
.Where(s => s.Unit != null)
.OrderBy(s => s.Unit)
.Select(s => new
{
Description = s.Unit + " - " + s.MakeModel
}).ToList();
ViewBag.Units = new SelectList(units);
//post:/create
ViewBag.Units = new SelectList(db.EquipmentLists.OrderBy(x => x.Unit + " - " + x.MakeModel));
create.cshtml
@Html.DropDownListFor(model => model.Unit, (SelectList)ViewBag.Units, "Select one...", htmlAttributes: new { @class = "form-control" })
不知道为什么要在视图中获得"{ }"
支架。只想摆脱它们。任何帮助将不胜感激。
您的查询正在创建一个名为 Description
的属性的匿名对象。
当您将SelectList
构造函数与单个参数(其中参数为 IEnumerable
)时,方法在集合中的每个项目上调用 .ToString()
来生成值并显示每个选项的文本),并且仅在集合包含的情况下适合简单类型(例如IEnumerable<string>
或IEnumerable<int>
)
更改构造函数,以使用接受dataValueField,
和dataTextField
ViewBag.Units = new SelectList(units, "Description", "Description");
另外,您可以直接使用
直接创建IEnumerable<SelectListItem>
ViewBag.Units = db.EquipmentLists
.Where(s => s.Unit != null)
.OrderBy(s => s.Unit)
.Select(s => new SelectListItem
{
Value = s.Unit + " - " + s.MakeModel,
Text = s.Unit + " - " + s.MakeModel,
});
并将视图调整为
@Html.DropDownListFor(m => m.Unit, (IEnumerable<SelectListItem>)ViewBag.Units, "Select one...", new { @class = "form-control" })
斯蒂芬说的是正确的,但让我详细说明。
ViewBag.[VAR] = new SelectList([list], [value], [text]);
使用此处详细介绍的SelectList
构造函数
SelectList(IEnumerable items, string dataValueField, string dataTextField);
只要您有一个继承Ienumerable的集合,它将与选择列表一起使用。dataValueField
指的是您想要的HTML value
属性所具有的任何内容,dataTextField
指的是您希望显示的任何内容。
与数据表对象一起使用这很方便,因为您可以将字段作为文本。例如:
public class Obj1
{
public int id {get; set}
public string field1 {get; set;}
public string field2 {get; set;}
public string DisplayField {get {return field1 + " " + field2;}}
}
//In your controller
public ActionResult Create()
{
...other code
List<Obj1> list = GetAllObj1(); //however you get the fields
ViewBag.Fields = new SelectList(list, "id", "DisplayField");
return View();
} ...
希望这对某些人有帮助。
请在控制器侧使用以下代码viewBag.units = db.EquipmentLists.Select(s => new SelectListItem {value = s.unit " - " s.makemodel,text = s.unit " - " s.makemodel});
);并在视图侧使用以下行@html.dropdownlistfor(m => m.unit,(iEnumerable)viewbag.units,"选择一个...",new {@class =" form-control"})