将对象的引用属性绑定到MVC3中的dropdownlist的最佳方法

时间:2011-12-17 18:23:18

标签: c# asp.net-mvc-3 drop-down-menu properties bind

我有一个这样的实体:

public class Asset
{
    public virtual string Name { get; set; }
    public virtual string SerialNumber { get; set; }
    public virtual string Manufacturer { get; set; }
    public virtual string Description { get; set; }
    public virtual Department Location { get; set; }
}

我尝试使用dropdownlistfor:

绑定“location”属性
 @Html.DropDownListFor(x => x.Location.Id, new SelectList(ViewBag.Departments, "Id", "Name", Model.Location), "--- empty ---")

但我需要能够将位置字段留空。问题是如何实现这一最佳方式?

2 个答案:

答案 0 :(得分:0)

DropDownListFor需要以下语法,当您将Location作为所选索引属性传递时,我发现了问题。

而不是这个

@Html.DropDownListFor(x => x.Location.Id, new SelectList(ViewBag.Departments, "Id", "Name", **Model.Location**), "--- empty ---")

试试这个

@Html.DropDownListFor(x => x.Location.Id, new SelectList(ViewBag.Departments, "Id", "Name", Model.Location == null ? 0 : Model.Location.Id), "--- empty ---")

答案 1 :(得分:0)

public class Asset
{
    public virtual string Name { get; set; }
    public virtual string SerialNumber { get; set; }
    public virtual string Manufacturer { get; set; }
    public virtual string Description { get; set; }
    public virtual Department Location { get; set; }
    public Asset(){
       this.Location=  new Department();
    }
}