'System.Web.Mvc.SelectListItem'不包含名为'id'#2的属性

Seb*_*n A 4 c# asp.net asp.net-mvc entity-framework razor

我有以下实体:

public class Entidad
{
    [Key]
    public int Id { get; set; }
    public string Nombre { get; set; }

    public virtual ICollection<Propiedad> Propiedades { get; set; }
}

public class Propiedad
{
    [Key]
    public int Id { get; set; }

    public virtual Entidad Entidad { get; set; }

    public string Codigo { get; set; }
    public string Nombre { get; set; }
    public string TipoDeDatos { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有这个控制器动作

public ActionResult Create()
{
    ViewBag.Entidad = new SelectList(db.Entidades);
    return View();
}
Run Code Online (Sandbox Code Playgroud)

在我看来:

<div class="form-group">
    @Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.Entidad.Id, new SelectList(ViewBag.Entidad, "id", "nombre", 0), "Seleccionar", new { @class = "form-control" })
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误:DataBinding:'System.Web.Mvc.SelectListItem'不包含名为'id'的属性.

我也试过Camel Case Id,但仍然是一样的.

小智 7

首先,您需要更改ViewBag属性的名称,以便它不与您的模型属性(说EntidadList)相冲突,然后在SelectList构造函数中指定要用作值和文本字段的属性

ViewBag.EntidadList = new SelectList(db.Entidades, "id", "nombre");
Run Code Online (Sandbox Code Playgroud)

然后在视图中使用

@Html.DropDownListFor(m => m.Entidad.Id, (SelectList)ViewBag.EntidadList, "Seleccionar", new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)

笔记:

  1. EntidadList已经是SelectList- 没有必要从中创建一个新的.
  2. SelectList构造函数中的最后一个参数(您设置它的位置"0")不是必需的并被忽略.在视图中选择的选项基于值Entidad.Id
  3. 您当前的使用情况ViewBag.Entidad = new SelectList(db.Entidades);在您不设定值和文本字段意味着它的创造SelectListItems与价值 System.Web.MVC.SelectListItem>(一string)不具有一个属性命名id,因此错误的观点,当你试图创建一个新的SelectList从它