我有以下实体:
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; }
}
我有这个控制器动作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Codigo,Nombre,TipoDeDatos")] Propiedad propiedad)
{
if (ModelState.IsValid)
{
db.Propiedades.Add(propiedad);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(propiedad);
}
并且在我看来:
<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>
但是,当我调试控制器时,Propiedad实体上的Entidad属性为NULL
答案 0 :(得分:1)
在Data方法的声明中,在Create方法的Bind中,你不包括Entidad属性,永远不会被绑定,只需删除Bind DataAnnotation或包含它。