Sponsored Ad

Tuesday, March 23, 2010

How to Write and Execute Client side JavaScript Code in C#

This is sample method in C# to write a JavaScript code and execute it. Just pass your message in this block of code and it will show alert message on the page.

In place of alert you can write your own JavaScript code. We made this method generic so that  we first checking for single quote in string, In case of hard coding the string we can by pass this step.

Let me know if you have any questions?

 

public static void Alert(string message)
       {
           // Cleans the message to allow single quotation marks
           string cleanMessage = message.Replace("'", "\'");
           string script = "<script type='text/javascript'>alert('" + cleanMessage + "');</script>";

           // Gets the executing web page
           Page page = HttpContext.Current.CurrentHandler as Page;

           // Checks if the handler is a Page and that the script isn't allready on the Page
           if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
           {
               page.ClientScript.RegisterClientScriptBlock(typeof(JavaScript), "alert", script);
           }
       }

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers