我猜我在这里错过了一个简单的原则,有人会很快指出。我基本上有一个 Person 对象,它包含一些基本属性,然后是几个 Lists<> 用于电话和地址。电话和地址各有一个类型(家庭/工作/等)。地址也有一个州和一个县。
当我执行管理操作时,我正在为 CountyId、StateProvinceID 等设置 ViewBag,但是当我有第二个地址或电话时,这些下拉列表似乎没有正确的选择值。
我确定这是我在这里做错的可悲基本的事情......
解决...
我知道我缺少一些基本的东西,答案是简单地为 Address 和 Phone 对象创建自定义视图模型。这些新的视图模型可以包含每个选择列表的列表...
模型样本
public CustomerModel()
{
IsActive = true;
if (Phones == null)
{
Phones = new List<Phone>();
}
if (Addresses == null)
{
Addresses = new List<Address>();
}
}
public Guid Id { get; set; }
public Guid OrganizationId { get; set; }
[Required]
public String FirstName { get; set; }
public String MiddleName { get; set; }
[Required]
public String LastName { get; set; }
[RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address.")]
public String EmailAddress { get; set; }
[DataType(DataType.Date)]
public DateTime? DateOfBirth { get; set; }
public List<Phone> Phones { get; set; }
public List<Address> Addresses { get; set; }
}
家长查看示例
<tbody id="tblAddressRows">
@foreach (var address in Model.Addresses)
{
Html.RenderPartial("_AddressRow", address);
}
</tbody>
部分视图样本
<td>
@Html.HiddenFor(a => a.Id)
@Html.DropDownList("AddressTypeId", ViewData["AddressTypeId"] as SelectList)
</td>
<td class="AddressLines">
@Html.EditorFor(a => a.AddressLine1)
@Html.EditorFor(a => a.AddressLine2)
</td>
<td>
@Html.EditorFor(a => a.City)
</td>
<td>
@Html.DropDownListFor(m => m.StateProvinceId, ViewData["StateProvinceId"] as SelectList, new {@class = "State"})
</td>
<td>
@Html.EditorFor(a => a.PostalCode, new {@class = "ZipCode"})
</td>
<td>
@Html.DropDownList("CountyId", ViewData["CountyId"] as SelectList, new {@class = "County"})
</td>
控制器样品
//
// GET: /Customer/Manage/5
public ActionResult Manage(Guid id)
{
CustomerModel customer = DataService.GetCustomer(id, HttpContext.User.Identity.Name);
if (customer == null)
{
return HttpNotFound();
}
ViewBag.AddressTypeId = new SelectList(DataService.GetOrganizationAddressTypes(HttpContext.User.Identity.Name), "Id", "Name");
ViewBag.PhoneTypeId = new SelectList(DataService.GetOrganizationPhoneTypes(HttpContext.User.Identity.Name), "Id", "Name");
ViewBag.StateProvinceId = new SelectList(DataService.GetStates(), "Id", "Name");
ViewBag.CountyId = new SelectList(DataService.GetCounties(0), "Id", "Name");
return View(customer);
}