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.
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:
EntidadList
is already a SelectList
- there is no need to create
a new one from it.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
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 itlate 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)