【发布时间】:2015-10-29 06:03:27
【问题描述】:
我正在为 WebForms 使用新的模型绑定功能,以及 .NET Framework 版本 4.5.1。 我希望实现的是,根据某些条件排除一些双向绑定。
我非常喜欢(希望现在很有名)blog post series, by Scott Guthrie。我使用Web Forms Model Binding Part 3: Updating and Validation (ASP.NET 4.5 Series)中的方法二实现了一个编辑页面
这是我所拥有的:(简化,在 ElementEdit.aspx 中):
<asp:FormView runat="server" ID="FormViewElement" RenderOuterTable="false" DefaultMode="Edit" DataKeyNames="ElementId"
ItemType="Business.Entities.Element"
SelectMethod="GetElement"
UpdateMethod="UpdateElement">
<EditItemTemplate>
<asp:Panel runat="server" DefaultButton="ButtonSpeichern">
<fieldset>
/*some databound controls*/
<asp:Panel runat="server" Visible="<%# !Item.CurrentElementData.SomeCondition() %>">
/*more databound controls*/
</asp:Panel>
/*the submit button ("ButtonSpeichern")*/
</fieldset>
</asp:Panel>
</EditItemTemplate>
</asp:FormView>
如您所见,使用“更多数据绑定控件”的包装内面板的可见性存在一个条件。只有当条件为真并且它们是可见的时,它们才应该绑定。否则它们不应该绑定也不改变值。
更新的工作方式类似于 Scott 的帖子(简化,在 xxPage.cs 中),它是 Type Element 的通用基类:
protected virtual bool UpdateEntity(int id) {
T existing = UseCase.GetItem(id); //gets the original element
TryUpdateModel(existing); //SHOULD NOT update the invisible databound controls, but does
ValidateExistingEntity(existing);
if (ModelState.IsValid) {
UseCase.Update(existing);
return true;
}
ShowErrors(ModelState);
return false;
}
这里,在调用TryUpdateModel()之后,隐形控件已经更新了模型,这是我想要避免的。
如何根据条件动态省略某些元素的数据绑定,即使将它们设置为不可见也无济于事?
更新: 我现在创建了一个解决方法,它今天为我解决了这个问题:我只是创建了两个 .aspx 页面,它们各自的代码在后面。根据用户应该成功编辑的字段,我首先调用相应的页面。
但是,这并不能解决根本问题,即条件数据绑定。
【问题讨论】:
标签: c# asp.net webforms controls model-binding