How to Set JavaScript Programmatically on a Page in ASP.NET with Parameters

Posted by Peter Kellner on May 03, 2009 · 2 mins read

Programmatically setting JavaScript into an ASP.NET page is very straight forward when you do it in code.  That is, in my case, I simply put it in the Page_Load event of the page and have it load from there.  I’m currently working on an ExtJS project that requires me to show some details on a page that I want to show with JavaScript.  I’ve nicely modularized all the JavaScript into a name space so the code that I want to include on my ASP.NET Page looks like the following:

<script type="text/javascript" language="javascript" >
    ASPWeb.newsGrid.loadTypeId = 229490;
    ASPWeb.newsGrid.init();
</script>

To put the same code in, but substitute the loadTypeId with something meanful, here is the C# code you need to put in your Page_Load C# code.

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LabelEntityType.Text = EntityTypeId.ToString();
                LabelEntityId.Text = EntityId.ToString();
            }
            // The JavaScript needs to be registed on every post back.  Not just first time.
            // Define the name and type of the client scripts on the page.
            const string csname1 = "LoadDetailsGridScript";
            Type cstype = this.GetType();
            // Get a ClientScriptManager reference from the Page class.
            ClientScriptManager cs = Page.ClientScript;
            // Check to see if the startup script is already registered.
            if (!cs.IsStartupScriptRegistered(cstype, csname1))
            {
                //ASPWeb.newsGrid.loadTypeId = 229490;
                //ASPWeb.newsGrid.init();
                const string cstext1 = 
                    "ASPWeb.newsGrid.EntityId = {0};ASPWeb.newsGrid.EntityTypeId = 1; ASPWeb.newsGrid.init();";
                cs.RegisterStartupScript(cstype, csname1, String.Format(cstext1, LabelEntityId.Text), true);
            }
        }

I found this code on line at this MSDN location.

http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx

Hope this Helps!!!