0

I have a user control, in the page load of the control I am doing this :

if (ViewState["Lib"] != null)
{
    cfg.Lib = (string)ViewState["Lib"];
}

This Lib property can be modified with a textbox like this :

protected void Lib_e_Changed(object sender, EventArgs e)
{
    cfg.Lib = Lib_e.Text;
    ViewState["Lib"] = Lib_e.Text;
}

I have written the following javascript in my ascx file :

alert('<%= cfg.Lib %>');

It will always return the default value even if I have changed the text in my textbox. My textbox is in an update panel and I have set AutoPostBack to true. Is there something I am missing to update my value ?

Stan
  • 391
  • 2
  • 5
  • 21

1 Answers1

1

It is happening because aspx page render

alert('<%= cfg.Lib %>');

before any assign you are performing on

cfg.Lib

to make it workable what you can do is .. register the script from server side like

    protected void Lib_e_Changed(object sender, EventArgs e)
    {
        cfg.Lib = Lib_e.Text;
        ViewState["Lib"] = Lib_e.Text;

        ScriptManager.RegisterStartupScript(updatePanelId, updatePanelId.GetType(), "AnyKey", "alert('" + cfg.Lib + "')", true);
       //ScriptManager.RegisterStartupScript(this, this.GetType(), "AnyKey", "alert('" + cfg.Lib + "')", true);
       //Page.ClientScript.RegisterStartupScript(this.GetType(),"AnyKey","alert('"+cfg.Lib +"')",true);  
    }
Moumit
  • 8,314
  • 9
  • 55
  • 59
  • I have written this (because of the update panel) but it never shows an alert : Page.ClientScript.RegisterStartupScript(this.GetType(), "AnyKey", "$(document).ready(function () {alert('" + cfg.Lib + "');var prm = Sys.WebForms.PageRequestManager.getInstance();prm.add_endRequest(function () {alert('" + cfg.Lib + "');});});", true); – Stan Mar 01 '16 at 14:29
  • I think it's almost working. I would need to replace the registered script. At first update of "cfg.Lib" it will work but if I update it again, it won't update the script and keep the old value. – Stan Mar 02 '16 at 08:52
  • Oh sure .. might be you need `updatePanelId, updatePanelId.GetType()` check my update and http://stackoverflow.com/questions/11643578/registerstartupscript-doesnt-work-with-scriptmanager-updatepanel-why-is-that – Moumit Mar 02 '16 at 09:09
  • Thank you a lot, it is now working, just a last question, is it replacing the registered script content or does it append the old registered script with the new one ? – Stan Mar 02 '16 at 09:23
  • i forgot man!! look on source of html page in browser .. and you can find it there.. – Moumit Mar 02 '16 at 10:35