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 on my edit view
<div class="form-group">
@Html.LabelFor(model => model.Entidad, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Entidad.Id, (SelectList)(ViewBag.EntidadList), "Seleccionar", new { @class = "form-control" })
</div>
</div>
However I get this error on the view
The ViewData item that has the key 'Entidad.Id' is of type 'System.Int32' but must be of type 'IEnumerable'. Description
my controllers are:
// GET: /GlobalAdmin/Propiedades/Create
public ActionResult Create()
{
ViewBag.EntidadList = new SelectList(db.Entidades, "id", "nombre");
return View();
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Propiedad propiedad = db.Propiedades.Find(id);
if (propiedad == null)
{
return HttpNotFound();
}
return View(propiedad);
}
You can using the following code.
In action method :
In view page :
If you want use the dropdownlist in edit view and select the item from database you can use the following code :
In edit page :
I hope this help you.