我在提交多个模型的表单上绑定时遇到问题。我有一份投诉表格,其中包括投诉信息以及一对多投诉人。我正在尝试提交表单,但在绑定时遇到错误。ModelState.IsValid 始终返回 false。
如果我调试并查看 ModelState 错误,我会得到一个消息:“EntityCollection 已被初始化。在对象图的反序列化过程中,只应调用 InitializeRelatedCollection 方法来初始化新的 EntityCollection”。
此外,在调试时,我可以看到投诉模型确实从表单提交中填充了投诉人,所以这部分似乎正在工作。
我不确定我正在做的事情是否无法使用默认的 ModelBinder,或者我是否只是没有以正确的方式去做。我似乎找不到任何具体的例子或文档。可以在此处的 stackoverflow 上找到一个非常相似的问题,但它似乎无法处理强类型视图。
控制器代码:
public ActionResult Edit(int id)
{
var complaint = (from c in _entities.ComplaintSet.Include("Complainants")
where c.Id == id
select c).FirstOrDefault();
return View(complaint);
}
//
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Complaint complaint)
{
if (!ModelState.IsValid)
{
return View();
}
try
{
var originalComplaint = (from c in _entities.ComplaintSet.Include("Complainants")
where c.Id == complaint.Id
select c).FirstOrDefault();
_entities.ApplyPropertyChanges(originalComplaint.EntityKey.EntitySetName, complaint);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
查看代码(这是由创建/编辑视图调用的局部视图,它也使用 Complaint 进行强类型化):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ProStand.Models.Complaint>" %>
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm()) {%>
<table cellpadding="0" cellspacing="0" class="table">
<tr>
<td>
<label for="DateReceived">Date Received:</label>
<%= Html.TextBox("DateReceived") %>
<%= Html.ValidationMessage("DateReceived", "*") %>
</td>
<td>
<label for="DateEntered">Date Entered:</label>
<%= Html.TextBox("DateEntered")%>
<%= Html.ValidationMessage("DateEntered", "*") %>
</td>
</tr>
<tr>
<td>
<label for="Concluded">Concluded:</label>
<%= Html.CheckBox("Concluded")%>
<%= Html.ValidationMessage("Concluded", "*") %>
</td>
<td>
<label for="IncidentDate">Incident Date:</label>
<%= Html.TextBox("IncidentDate")%>
<%= Html.ValidationMessage("IncidentDate", "*") %></td>
</tr>
</table>
<hr />
<table>
<% if (Model != null) {
int i = 0;
foreach (var complainant in Model.Complainants){ %>
<%= Html.Hidden("Complainants[" + i + "].Id", complainant.Id)%>
<tr>
<td>
<label for="Surname">Surname:</label>
<%= Html.TextBox("Complainants[" + i + "].Surname", complainant.Surname)%>
<%= Html.ValidationMessage("Surname", "*")%>
</td>
<td>
<label for="GivenName1">GivenName1:</label>
<%= Html.TextBox("Complainants[" + i + "].GivenName1", complainant.GivenName1)%>
<%= Html.ValidationMessage("GivenName1", "*")%>
</td>
</tr>
<% i++; %>
<% }} %>
<tr>
<td colspan=2>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>