使用以下模型
public class State
{
public int StateId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class City
{
public int CityId { get; set; }
public string Name { get; set; }
public State state { get; set; }
}
和以下视图
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>City</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.CityId)
@Html.HiddenFor(model => model.state.StateId)
@Html.HiddenFor(model => model.state.Name)
@Html.HiddenFor(model => model.state.Code)
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
我看到State
是我的控制器中的NULL
public ActionResult Edit([Bind(Include = "CityId,Name")] City city)
{
// City.State is NULL and ModelSAtate.IsValid is FALSE
if (ModelState.IsValid)
{
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(city);
}
以此为单位, City.State
是 NULL
。
我知道将ModelState.IsValid
转到TRUE
的解决方法,但我喜欢知道MVC视图中Handing Object属性的正确方法。
如果您想在操作中捕获State
实体,则应添加这些隐藏的属性,作为City
@Html.HiddenFor(model => model.state.StateId)
@Html.HiddenFor(model => model.state.Name)
@Html.HiddenFor(model => model.state.Code)
编辑:我还必须删除Bind()
部分,以便我的动作看起来像
public ActionResult Edit(City city)
每当您尝试将请求从视图处理到控制器时,MVC路由都会尝试根据您的路由配置确定要调用的控制器操作。该作业被分配给ControllerActionInVoker。成功确定要调用哪种动作后,现在默认模型活页夹可以正确地控制模型。
默认模型绑定(DefaultModelBinder)按以下顺序工作: -
-
request.form-表格中提交的值
-
routedata.values-路由值,例如ID IN/雇员/edit/{id}
-
request.querystring-从url的查询字符串部分提取的数据
-
request.files-上传文件
有一些方法可以自定义您的绑定行为,您可能会发现这篇文章很有趣-https://mono.software/2017/02/09/model-binding-asp-net-mvc/
但是,出于您的问题,@marusyk的给定答案足够足够。快乐编码...