假设您有以下对象:
public class Address
{
public String Line1 { get; set; }
public String Line2 { get; set; }
public String City { get; set; }
public String State { get; set; }
public String ZipCode { get; set; }
public Address()
{
}
}
public class Contact
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Telephone { get; set; }
public Address BillingAddress { get; set; }
public List<Address> ShippingAddresses { get; set; }
public Contact()
{
// Assume anything that _could_ be null wouldn't be. I'm excluding
// most "typical" error checking just to keep the examples simple
this.BillingAddress = new Address();
this.ShippingAddresses = new List<Address>();
}
}
假设属性用[Required]
,[Display]
和其他属性装饰。
然后我的控制器(为了演示而简化):
public ActionResult Edit(String id)
{
Contact contact = ContactManager.FindByID(id);
return View(model: contact);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact contact)
{
if (ModelState.IsValid) //always fails
{
ContactManager.Save(contact);
return RedirectToAction("Saved");
}
return View(model: contact);
}
我经常看到在 MVC 中编辑这样的对象的演示,但他们不断地将对象的集合分解为自己的形式(例如,编辑联系人,然后编辑联系人的特定地址)。另一方面,我试图在同一页面内编辑所有这些信息,但没有成功。例如:
@model Contact
// simplified for brevity
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.FirstName): @Html.EditorFor(x => x.FirstName)
@Html.LabelFor(x => x.LastName): @Html.EditorFor(x => x.LastName)
@Html.LabelFor(x => x.Telephone): @Html.EditorFor(x => x.Telephone)
<div>
@Html.LabelFor(x => x.BillingAddress.Line1): @Html.EditorFor(x => x.BillingAddress.Line1)
@Html.LabelFor(x => x.BillingAddress.Line2): @Html.EditorFor(x => x.BillingAddress.Line2)
@Html.LabelFor(x => x.BillingAddress.City): @Html.EditorFor(x => x.BillingAddress.City)
@Html.LabelFor(x => x.BillingAddress.State): @Html.EditorFor(x => x.BillingAddress.State)
@Html.LabelFor(x => x.BillingAddress.ZipCode): @Html.EditorFor(x => x.BillingAddress.ZipCode)
</div>
<div>
@foreach (Address addr in Model.ShippingAddresses)
{
<div>
@Html.LabelFor(x => addr.Line1): @Html.EditorFor(x => addr.Line1)
@Html.LabelFor(x => addr.Line2): @Html.EditorFor(x => addr.Line2)
@Html.LabelFor(x => addr.City): @Html.EditorFor(x => addr.City)
@Html.LabelFor(x => addr.State): @Html.EditorFor(x => addr.State)
@Html.LabelFor(x => addr.ZipCode): @Html.EditorFor(x => addr.ZipCode)
</div>
}
</div>
}
我一直遇到的问题是ModelState.IsValid
当我去保存信息时永远不会过去。这样做有诀窍,还是只是在 MVC 领域之外?我想获取一个对象Contact
并将所有信息转储在一页上进行编辑,并成功地重新保存它,但我似乎无法让它工作。(我的下一步是绑定 ajax,以便您可以在该页面上动态添加/删除“ShipingAddresses”,但我需要先保存才能工作——KISS)
问题:
ModelState.IsValid
几乎总是错误的- 集合项的表单元素通常具有相同的名称,因此在此演示
Line1
中,ShippingAddresses
集合中的每个都转储到页面,name="addr_Line1"
而不是ShippingAddresses[0]_Line1
像我期望的那样。