Loading usercontrol on runtime and reloading the page
On my page I have a placeholder where I load a usercontrol when I select an item in dropdownlist.
protected void ddlLoadCtr_SelectedIndexChanged(object sender, EventArgs e)
{
Control userControl = LoadControl("../AleSettings1.ascx");
plchldSettingsControl.Controls.Add(userControl);
}
If I press F5 (IE) after user control was rendered, I get IE's warning window that IE needs to resend the information....
How can I prevent it and why does it happen?UPDATE:
Maybe there is another approach? I want to load specific control (with it's markup) when user selects it from the dropdownlist.
if a postback is made the control shouldn't disappear(开发者_如何学Conly if another control was selected from the dropdownlist)Everything is inside update panel!
it happens because when you do a refresh you are resending the last request to the server. In this case the event that changes the index in the drop down. You cannot prevent the browser from asking
ASP.NET WebForms uses "postbacks". This means that whenever it processes an "event", such as selecting an item in a select list, it does an HTTP POST back to the server to get the new HTML.
This allows it to save state between different versions of the page, but means F5 will be a POST which the browser will warn you of.
A way around this to use POST-then-REDIRECT and handle the persistency of the controls yourself. If it's only one control, e.g. adding the control, it can be done by checking the query string in Page_Load
to see whether you need to load the control:
protected void Page_Load(object sender, EventArgs e)
{
if Request.QueryString["ddlLoadCtr"] = "1":
plchldSettingsControl.Controls.Add(LoadControl("../AleSettings1.ascx"));
}
and then redirect back to the page instead of using the postback:
protected void ddlLoadCtr_SelectedIndexChanged(object sender, EventArgs e)
{
var newUrl = Request.RawUrl + "?ddlLoadCtr=1";
Response.Redirect(newUrl);
}
Other ways of saving the state - apart from the query parameters - include cookies and session variables. These have the drawback of not being bookmarkable.
In any case this means you don't get to use ASP.NET's automatic state management of the controls.
精彩评论