我有以下 [HttpGet] Create() 方法:
public ActionResult Create(int? parentId)
{
var model = new CreatePersonViewModel();
// pull parent from db
var parent = _db.Persons.FirstOrDefault(s => s.Id == parentId);
model.Parent = parentSet;
return View("Create", model);
}
如果我从另一个人的详细信息页面创建一个新人,我会传入该父人的 ID,然后构造一个包含父人的 viewModel。
POST 看起来像这样:
[HttpPost]
public ActionResult Create(CreatePersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var parent = viewModel.Parent; // This is always null for some reason
var person = new Person() { Name = viewModel.Name };
// if it has a parent, build new relationship
if (parent != null)
{
person.Parent = parent;
parent.Children.Add(person);
};
_db.Save();
return RedirectToAction("detail", "person", new { personId = person.Id });
}
return View(viewModel);
}
由于某种原因,被推回 POST 方法的 viewModel 永远不会包含在 GET 控制器方法中定义的 Parent。我如何告诉 MVC 将父级从 GET 推送到 POST,而不会用父级的隐藏字段混淆视图?
如果有帮助,我的观点是:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>CreatePersonViewModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}