我试图更新旧的Web窗体应用程序以使用4.5中添加的新模型绑定功能,类似于MVC绑定功能。ASP.NET Web Forms 4.5模型绑定模型包含集合
我在制作可编辑的FormView时遇到了麻烦,它呈现的是包含简单成员和包含其他模型集合的成员的单个模型。我需要用户能够编辑父对象的简单属性和子集合的属性。
问题是在代码尝试更新模型时,模型绑定后子集合(ProductChoice.Extras
)始终为空。
这里是我的模型:
[Serializable]
public class ProductChoice
{
public ProductChoice()
{
Extras = new List<ProductChoiceExtra>();
}
public int Quantity { get; set; }
public int ProductId { get; set; }
public List<ProductChoiceExtra> Extras { get; set; }
}
[Serializable]
public class ProductChoiceExtra
{
public int ExtraProductId { get; set; }
public string ExtraName { get; set; }
public int ExtraQuantity { get; set; }
}
背后我的用户控件代码:
public partial class ProductDetails : System.Web.UI.UserControl
{
private Models.ProductChoice _productChoice;
protected void Page_Load(object sender, EventArgs e)
{
_productChoice = new Models.ProductChoice()
{
Quantity = 1,
ProductId = 1
};
_productChoice.Extras.Add(new Models.ProductChoiceExtra()
{
ExtraProductId = 101,
ExtraName = "coke",
ExtraQuantity = 1
});
_productChoice.Extras.Add(new Models.ProductChoiceExtra()
{
ExtraProductId = 104,
ExtraName = "sprite",
ExtraQuantity = 2
});
}
public Models.ProductChoice GetProduct()
{
return _productChoice;
}
public void UpdateProduct(Models.ProductChoice model)
{
/* model.Extras is always null here, it should contain two ProductChoiceExtra objects */
if (TryUpdateModel(_productChoice) == true)
{
}
}
}
我的控制标记:
<div id="selectOptions">
<asp:FormView runat="server" ID="fvProductSelection" DefaultMode="Edit"
ItemType="Models.ProductChoice"
SelectMethod="GetProduct"
UpdateMethod="UpdateProduct" >
<EditItemTemplate>
<asp:linkbutton id="UpdateButton" text="Update" commandname="Update" runat="server"/>
<asp:HiddenField runat="server" ID="ProductId" Value="<%# BindItem.ProductId %>" />
<asp:TextBox Text ="<%# BindItem.Quantity %>" ID="Quantity" runat="server" />
<asp:Repeater ID="Extras" ItemType="Models.ProductChoiceExtra" DataSource="<%# BindItem.Extras %>" runat="server">
<ItemTemplate>
<asp:HiddenField Value="<%# BindItem.ExtraProductId %>" ID="ExtraProductId" runat="server" />
<asp:Label Text="<%# BindItem.ExtraName %>" ID="Name" runat="server" />
<asp:TextBox Text="<%# BindItem.ExtraQuantity %>" ID="Quantity" runat="server" />
</ItemTemplate>
</asp:Repeater>
</EditItemTemplate>
</asp:FormView>
</div>
我试图使Extras
属性BindingList
而不是List
,但它没有马如有任何差异,Extras
集合未在UpdateProduct
方法中绑定。
你不能尝试只传入模型ProductChoice。 EG: 公共无效的UpdateProduct(ProductChoice模型) {} 好 – izip
问题@PaulD:我原以为这FormView控件/中继器的做法是很常见的(我的做法是相同的你) - 但我没有也能够破解这一个。 – Merenzo
我试图实现一个自定义['System.Web.ModelBinding.IValueProvider'](http://msdn.microsoft.com/en-us/library/system.web.modelbinding.ivalueprovider(v = vs.110).aspx ),为了对TryUpdateModel()使用[overload](http://msdn.microsoft.com/en-us/library/hh140347(v = vs.110).aspx),但是我的'IValueProvider'实现陷入了一个无限递归循环,因为它反映了它通过对象属性的方式...... – Merenzo