发行者具有作为相关字段的 KeyEntity。我的代码有效,但我认为除了从数据库加载实体之外,必须有更好的方法来更新相关字段。ViewModeling 和模板应该有问题...在此先感谢。
操作视图模型
public class OpViewModel
{
public Connect.Models.Issuer Issuer { get; set; }
public IEnumerable<SelectListItem> KeyEntities { get; set; }
public OpViewModel() { }
public OpViewModel(Connect.Models.Issuer issuer,
IEnumerable<Jose.Models.KeyEntity> key_entities)
{
this.Issuer = issuer;
this.KeyEntities = key_entities.Select(k =>
new SelectListItem()
{
Selected = (k.Id == issuer.KeyEntity.Id),
Text = k.Id.ToString(),
Value = k.Id.ToString()
});
}
}
Op/Edit.chtml(剃刀)
@model AdConnect.Models.OpViewModel
@using (Html.BeginForm()) {
<div class="editor-field">
@Html.DropDownListFor(model => model.Issuer.KeyEntity.Id,
Model.KeyEntities)
</div>
}
操作控制器
[HttpPost]
public ActionResult Edit(Models.OpViewModel obj)
{
if (ModelState.IsValid)
{
// This works for most data fields of Issuer, but KeyEntity's Id
// (dbo.Issuers.KeyEntity_Id) is not updated.
//
// ctx.Entry(obj.Issuer).State = System.Data.EntityState.Modified
// So load Issuer and KeyEntity from the database and update.
var issuer = ctx.Issuers.Find(obj.Issuer.Id);
if (obj.Issuer.KeyEntity != null)
{
issuer.KeyEntity =
ctx.KeyEntities.Find(obj.Issuer.KeyEntity.Id);
}
ctx.Entry(issuer).CurrentValues.SetValues(obj.Issuer);
ctx.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}