我正在尝试发布一些嵌套对象。
我有一个Cart类,里面有两个属性ShippingAddress和BillingAddress。地址的类型为ContactInformation。
在一个视图上,我包括一个局部视图(AddressForm),我将ShipppingAddress传递给该局部视图;在另一个视图上,我想要显示相同的局部视图,但我将其传递给BillingAddress。
现在,当我填写ShippingAddress时,我会将整个Cart对象传递给post方法,但ShippingAddress为空。
我试图根据我在那里传递的地址类型来设置ViewData.TemplateInfo.HtmlFieldPrefix。因此,当我传递ShippingAddress时,HtmlFieldPrefix是“ ShippingAddress”。元素的所有id确实具有ShippingAddress前缀。在提交后的post方法上,我有这个[Bind(Prefix =“ ShippingAddress”)] CartViewModel模型,但送货信息仍然为空。
这是一些代码
购物车型号
public class CartViewModel
{
public ContactInformation ShippingAddress { get; set; } = new ContactInformation(EAddressType.ShippingAddress);
public ContactInformation BillingAddress { get; set; } = new ContactInformation(EAddressType.BillingAddress);
}
地址模型
public class ContactInformation
{
public EAddressType AddressType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public ContactInformation(EAddressType addressType)
{
AddressType = addressType;
}
}
这是我要在其中显示送货地址表格的视图
@model CartViewModel
@using (Ajax.BeginForm(InformationFormSubmit, Cart, null,
new AjaxOptions
{
HttpMethod = "POST",
AllowCache = false,
InsertionMode = InsertionMode.Replace,
UpdateTargetId = _InformationForm,
}, htmlAttributes: new { }))
{
<div id="_InformationForm">
@Html.Partial(_InformationForm, Model)
</div>
}
_InformationForm看起来像这样
@model CartViewModel
@Html.Partial(_AddressForm, Model.ShippingAddress)
<button type="submit" >@Resource.ContinueToShipping</button>
最后是我的地址表格
@model ContactInformation
ViewData.TemplateInfo.HtmlFieldPrefix = Model.AddressType == EAddressType.ShippingAddress ? "ShippingAddress" : "BillingAddress";
@Html.HiddenFor(m => m.AddressType)
@Html.TextBoxFor(a => a.FirstName, htmlAttributes: new { id = Html.IdFor(a => a.FirstName)})
@Html.TextBoxFor(a => a.LastName, htmlAttributes: new {id = Html.IdFor(a => a.LastName) })
@Html.TextBoxFor(a => a.Address, htmlAttributes: new { id = Html.IdFor(a => a.Address)})
@Html.TextBoxFor(a => a.City, htmlAttributes: new { id = Html.IdFor(a => a.City)})
@Html.TextBoxFor(a => a.PostalCode, htmlAttributes: new {id = Html.IdFor(a => a.PostalCode) })
我的帖子操作如下
[HttpPost]
public virtual ActionResult InformationFormSubmit([Bind(Prefix = "ShippingAddress")] CartViewModel model)
{
if (ModelState.IsValid)
{
CartViewModelEntity.ShippingAddress.FirstName = model.ShippingAddress.FirstName;
CartViewModelEntity.ShippingAddress.LastName = model.ShippingAddress.LastName;
CartViewModelEntity.ShippingAddress.Address = model.ShippingAddress.Address;
CartViewModelEntity.ShippingAddress.City = model.ShippingAddress.City;
CartViewModelEntity.ShippingAddress.PostalCode = model.ShippingAddress.PostalCode;
}
return PartialView(_InformationForm, model);
}
但是,当然,在发布操作中,ShippingAddress为空。
不知道我在做什么错..
感谢帮助