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

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!!!

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP since 2007. In addition, he's a multi-course video author at Pluralsight. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. ShareeMajakosofdjzal says:

    do you even know how to use a computer

  2. quelle info !

  3. Thanks for sharing information with us. I am glad to see this code. I am looking for same kinda from many days.

Follow

Get every new post delivered to your Inbox

Join other followers: