获取控制器方法:
public ActionResult Create(int? parentId)
{
var model = new CreatePersonViewModel();
// pull set from db
var parent = _db.Persons.FirstOrDefault(s => s.PersonId == parentId);
if (parent != null)
{
model.ParentId = parent.PersonId;
}
return View("Create", model);
}
邮政:
public ActionResult Create(CreatePersonViewModel viewModel) // viewModel.ParentId is 0 when it's passed to this method from the view, even though I didn't set it, and it's null coming from GET.
{
//bla bla
}
我的观点:
@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>
@Html.HiddenFor(model => model.ParentId) // tried with second parameter of "null" as well
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
知道为什么视图在该属性中返回 0 值以应对它应该为空的情况吗?我没有任何细节要在这里添加,但表单验证要求更多文本,所以在这里。