Client Side Script in a .NET Web Part

Quick, a little snippet on adding client side scripts (javascript) in a web part or ASP.NET page. And the link to MSDN where I found this wonderful information. My script was small, basically an alert to tell the user he/she is stupid. So I embedded the script in the Web Part. It worked. Here is my code snippet, since the one on MSDN was using old function to register the client script.

    private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";
    private const string EmbeddedScriptFormat =
          "<script language=javascript>alert('Bye Bye');</script> ";

    public WebPart_ClientScript()
    {
       this.PreRender += new EventHandler(WebPart_ClientScript_PreRender);
    }

    private void WebPart_ClientScript_PreRender(object sender , System.EventArgs e )
    {

            if (!Page.ClientScript.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
              Page.ClientScript.RegisterClientScriptBlock(typeOf(WebPart_ClientScript), ByeByeIncludeScriptKey, EmbeddedScriptFormat);
    }

Note that James.ToString() says not to use this.GetType but rather typeOf(ControlName) where control name is the web part. So the above just tosses up an alert that happens when the page loads. Although, if you did want a function in there, to have it be called, you add the OnClientClick attribute to the asp tag.

    <asp:Button runat="server" Text="Oh, Click me.." OnClientClick="ShowAlert()" />

And that “ShowAlert()” can be any function name. Simple enough.

Tags: , , ,

Leave a Reply