【发布时间】:2012-01-27 20:01:36
【问题描述】:
假设你有以下对象:
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”,但我需要先保存才能工作--K.I.S.S)
问题:
-
ModelState.IsValid几乎总是假的 - 集合项的表单元素通常具有相同的名称,因此在此演示中,
ShippingAddresses集合中的每个Line1都以name="addr_Line1"的形式转储到页面,而不是像我期望的那样ShippingAddresses[0]_Line1。
【问题讨论】:
-
您可以将
[AcceptVerbs(HttpVerbs.Post)]缩短为[HttpPost] -
Contact是否有默认构造函数?
-
@ChrisS:是的,为了论证,它们都有空的构造函数。
标签: razor asp.net-mvc-4 asp.net-mvc-templates