我正在使用.NET Framework版本4.5.1的WebForms的新模型绑定功能。我的目标是,基于某些条件排除部分双向绑定。
我非常喜欢(希望现在已经出名的)Scott Guthrie的博客系列。我使用Web Forms Model Binding Part 3: Updating and Validation (ASP.NET 4.5 Series)中的第二种方法实现了一个编辑页面。
这是我拥有的东西(在ElementEdit.aspx中简化):
这是我拥有的东西(在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页面。根据用户应成功编辑哪些字段,我首先调用适当的页面。
然而,这并不能解决条件数据绑定的根本问题。