I’m adding my js files to header on code-behind like this:
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
HtmlGenericControl js = new HtmlGenericControl("script");
js.Attributes["type"] = "text/javascript";
js.Attributes["src"] = "/js/jquery.js";
js.ID = "jquery";
js.EnableViewState = true;
Page.Header.Controls.Add(js);
}
}
this works pretty well on page load, but I lose my js on postbacks, I was expecting my control persist with HtmlGenericControl’s ViewState enabled…
any way to persist ViewState on header or do I have to remove if (!IsPostBack) condition to add js every time?
your control is added dynamically and only when
!IsPostBack, ViewState can keep values and status but the control has to exists by its own on the page.In your case after a post back the control will not be added so even if the
ViewStatecontained its status, there is no control to attach this status to.