我在CodeFirst脚手架ASP.NET MVC站点中使用了以下模型(简化):
public class Order
{
public Guid ID {get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity), Display(Name = "Order Number")]
public int Number { get; set; }
public DateTime Date { get; set; }
}
public class OrderLine
{
public Guid ID { get; set; }
public Guid OrderID { get; set; }
public virtual Order Order { get; set; }
}
Order
不包含字符串属性,因此在OrderLine的“编辑”视图中,GUID显示在下拉列表中,但我想显示Number
属性
<div class="form-group">
@Html.LabelFor(model => model.OrderID, "Order Number", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("OrderID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.OrderID, "", new { @class = "text-danger" })
</div>
</div>
可以在模型级别定义哪个属性应该被认为是在下拉列表中显示,还是DropDownList帮助器在此场景中指定文本的语法?
答案 0 :(得分:2)
可以在模型级别定义应该考虑在下拉列表中显示哪个属性
您可以创建SelectList
的实例,并将其传递给DropDownList
Helper类的Html
方法,如下所示:
ViewBag.Orders = new SelectList(db.Orders // select Orders from databse here
, "OrderID" // value property inside the order class
, "Name"); // display text property in the dropdown
并在下面的视图中使用它
@Html.DropDownList("OrderID", ViewBag.Orders as SelectList, htmlAttributes: new { @class = "form-control" });