我有一个搜索表单,它提供了许多不同的搜索选项,例如'在自然名称上搜索','在合法名称上搜索','在地址上搜索'等。这些由静态“工厂”方法定义PropertySearchOption
类。每个搜索选项指定包含该optiom所需的搜索字段的用户控件,例如,自然名称选项具有名称和姓氏字段。所使用的搜索选项由主搜索页上的RadioButtonList确定,当选择在此列表中更改时,我动态加载所需的用户控件。我的问题是,我无法找到一种方法来保存动态控制及其搜索字段的视图状态。下面是我使用的核心代码:如何显式维护动态创建的用户控件的视图状态?
<asp:RadioButtonList ID="searchTypeOptions" runat="server" AutoPostBack="true" RepeatDirection="Horizontal" RepeatLayout="Flow" OnSelectedIndexChanged="SearchTypeOptionsSelectedIndexChanged">
<asp:ListItem Value="NaturalName">Name (Natural)</asp:ListItem>
<asp:ListItem Value="LegalName">Legal Name (Business)</asp:ListItem>
<asp:ListItem Value="ErfDetails">Erf Details</asp:ListItem>
<asp:ListItem Value="PhysicalAddress">Physical Address</asp:ListItem>
<asp:ListItem Value="FarmDetails">Farm</asp:ListItem>
</asp:RadioButtonList>
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
var typeOption = searchTypeOptions.SelectedItem;
if (typeOption == null)
{
searchTypeOptions.SelectedValue = "ErfDetails";
LoadSearchForm();
}
}
}
protected void SearchTypeOptionsSelectedIndexChanged(object sender, EventArgs e)
{
LoadSearchForm();
}
protected virtual void LoadSearchForm()
{
SearchOption = (PropertySearchOption)typeof(PropertySearchOption).GetProperty(searchTypeOptions.SelectedValue, BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null);
searchFormPlaceHolder.Controls.Clear();
var searchForm = LoadControl(SearchOption.FormControlUrl);
searchFormPlaceHolder.Controls.Add(searchForm);
searchTypeLabel.Text = SearchOption.Description;
}
我不得不的EnableViewState设置为false searchFormPlaceHolder
,否则我得到一个视图状态异常,当我尝试改变当前的选项,这样的动态选择搜索表单工作正常。但是,在按钮上单击回发来执行搜索,我失去了搜索表单,因为它只在第一次加载时在Page_Init中创建,而不是回发。如果我将LoadSearchForm
放置在if块之外,它将失败,因为在回发时,单选按钮列表的SelectedValue
为空。
除了逃跑之外,我该怎么办,或者该怎么办?