我有一个这样的实体:
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 ---")
但我需要能够将位置字段留空。问题是如何实现这一最佳方式?
答案 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();
}
}