【发布时间】:2015-08-28 20:41:50
【问题描述】:
我有以下实体:
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; }
}
在我的编辑视图中
<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>
但是我在视图上得到了这个错误
具有键“Entidad.Id”的 ViewData 项属于“System.Int32”类型,但必须属于“IEnumerable”类型。 说明
我的控制器是:
// 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);
}
【问题讨论】:
-
你能显示 ViewBag.EntidadList 的定义吗?
-
你能把查询放到 ViewBag.EntidadList
-
您收到该错误的原因是
ViewBag.EntidadList是null。在Edit()方法中,您不会将SelectList分配给ViewBag.EntidadList。您需要按照您的Create()方法进行操作。
标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-3