我有一个网页自定义控件
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"
Inherits="WebApplication5.WebUserControl1" %>
<asp:DropDownList ID="ddlnew" AutoPostBack="true" runat="server"
onselectedindexchanged="ddlnew_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text2" />
</asp:DropDownList>
并在Default.aspx页面上
<asp:Button Text="PostBack" ID="btnPost" runat="server"
onclick="btnPost_Click" />
和Default.aspx.cs
protected void btnPost_Click(object sender, EventArgs e)
{
WebUserControl1 uc = (WebUserControl1)Page.LoadControl("~/WebUserControl1.ascx");
PlaceHolder.Controls.Add(uc);
}
当我们从下拉列表中选择任何项目时,它会回发并且控件会从页面隐藏
所以请帮助我们如何防止隐藏
感谢
答案 0 :(得分:4)
动态创建控件must be recreated on every postback
,当您意识到每个回发创建Page
类的新实例时,在此实例中,您必须每次都重新创建所有控件,变得更加明显。
Here is a good article on this
Another post on this that i answered
要维持回发之间的状态,您可以使用ViewState
或ControlState
答案 1 :(得分:2)
protected void ddlnew_SelectedIndexChanged(object o, EventArgs e)
{
ViewState["ddlnew_value"]=ddlnew.selectdeitem;
}
比在页面加载pu
If(IsPostBack)
{
if(ViewState["ddlnew_value"]!=null)
{
ddlnew.selecteditem=ViewState["ddlnew_value"];
}
}
这应该有效
答案 2 :(得分:1)
在ASP.NET中,动态加载的控件需要引起一些注意,因为它们在回发中的行为。您必须在回发或check that on which control's is generating postback you will load the control or not..
检查这些文章(特别是MSDN参考):
An Extensive Examination of User Controls - MSDN
Loading UserControl Dynamically in UpdatePanel
Maintain Viewstate for Dynamic controls across the postback
答案 3 :(得分:0)
1)您需要在页面上启用视图状态。
2)与本文中提及的其他人一样,您需要重新创建动态加载的用户控件。
以下是一个例子:
protected void Page_Load(object sender, EventArgs e)
{
Render();
}
渲染方法:
private void Render()
{
var list = Helpers.Content.Lists.GetListByTitle();
if (list != null && list.Items.Count > 0)
{
this.divContainer.Controls.Clear();
var i = 1;
list.Items.ForEach(question =>
{
this.divContainer.Controls.Add(RenderQuestion(question, i));
i++;
});
}
}
渲染问题方法:
private Control RenderQuestion(Entities.Modules.Item question, int count)
{
// Create question control
var q = (Custom.Widgets.ActionPlans.New.Question)LoadControl("~/Custom/Widgets/ActionPlans/New/Question.ascx");
// Render question
q.Render(question, count);
return q;
}
希望这有帮助。