'System.Web.Mvc.SelectListItem' does not contain a property with the name 'id' #2

asp.net asp.net-mvc c# entity-framework razor

Question

I have the following entities:

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; }
}

And I have this controller action

public ActionResult Create()
{
    ViewBag.Entidad = new SelectList(db.Entidades);
    return View();
}

and on my view:

<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>

However I get this error: DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'id'.

I also tried with Camel Case Id but still the same.

1
4
6/12/2015 12:37:19 AM

Accepted Answer

Firstly you need to change the name of your ViewBag property so it does not conflict with your model property (to say EntidadList) and then in the SelectList constructor, specify the properties to use as the value and text fields

ViewBag.EntidadList = new SelectList(db.Entidades, "id", "nombre");

Then in the view use

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

Notes:

  1. EntidadList is already a SelectList - there is no need to create a new one from it.
  2. The last parameter in the SelectList constructor (where your set it to "0") is not required and is ignored. The option that is selected in the view is based on the value of Entidad.Id
  3. Your current usage of ViewBag.Entidad = new SelectList(db.Entidades); where your do not set the value and text fields means its creating SelectListItems with a value of System.Web.MVC.SelectListItem> (a string) which does not have a property named id, hence the error in the view when you attempt to create a new SelectList from it
9
6/11/2015 11:27:33 PM

Popular Answer

late reply, sorry. Declare ViewBag.List as List<> in the controller. then use it to create the select list in the view new SelectList(Viewbag.List, "ID", "Property", optional selected value)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow