In my ASP.NET application - having ViewState enabled - I can reset inputs by simply setting them again. Here is a basic simple sample that works:
_TEST.aspx
<asp:ScriptManager runat="server" />
<asp:DropDownList ID="ddl" runat="server" DataSource='<%# new string[] { "A", "B", "C" } %>' />
<asp:Button ID="b" runat="server" UseSubmitBehavior="false" OnClick="b_Click" Text="Test 1" />
_TEST.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
this.ddl.SelectedValue = "B";
}
protected void b_Click(object sender, EventArgs e)
{
Console.WriteLine("Updated");
}
In this example ddl
will be bound with "A", "B" and "C" on Page_Load
and it will always select "B". So when you change the selection and submit, it will be reset. Imagine this is used to reset some controls on specific conditions.
In my case I need this kind of behavior on a dynamically loaded UserControl
that is added to a Placeholder
. Because a Placeholder
does not persist the content I need to recreate the controls on every postback. The ViewState
seems to be okay with it. Here is a sample:
_TEST.aspx
<asp:ScriptManager runat="server" />
<asp:PlaceHolder ID="ph" runat="server" />
_TEST.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
_TESTUC uc = (_TESTUC)this.Page.LoadControl("~/Controls/_TESTUC.ascx");
this.ph.Controls.Add(uc);
}
_TESTUC.ascx
<asp:DropDownList ID="ddl" runat="server" DataSource='<%# new string[] { "A", "B", "C" } %>' />
<asp:Button ID="b" runat="server" UseSubmitBehavior="false" OnClick="b_Click" Text="Test 2" />
_TESTUC.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
this.ddl.SelectedValue = "B";
}
protected void b_Click(object sender, EventArgs e)
{
Console.WriteLine("Updated");
}
Again, on every postback I want to reset the selection of the DropDownList
for test purposes, but interestingly it remembers my selection.
What can I do to fix this?
While writing this question I came to the solution but decided to post it for other peoples, anyways.
It seems ASP.NET will load the ViewState
between Page_Init
and Page_Load
in controls that are defined in ASPX, while it loads the ViewState
between Page_Load
and Page_LoadComplete
in controls that are loaded in code-behind.
Setting the values in Page_LoadComplete
solves the issue:
protected void Page_Init(object sender, EventArgs e)
{
this.Page.LoadComplete += new EventHandler(this.Page_LoadComplete);
}
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
this.ddl.SelectedValue = "B";
}
protected void b_Click(object sender, EventArgs e)
{
Console.WriteLine("Updated");
}