Thursday 3 January 2013

Calling javascript function from CodeBehind with C#


Javascript works from the client side while server code requires server processing. 
It is not possible to direcly invoke a client event through a server event. However there exists a fairly simple methods to achieve this. I will explain one simple way to do it.

Injecting a javascript code into a label control

This is one of the simplest method to call a javascript function from code behind. You need to do the following:

1.     Create a new website project
2.     Add a label and button control on your Default.aspx page
3.     You body part of the markup should now look something like this: 

<body> 
    <form id="form1" runat="server"> 
    <div> 
        <asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label> 
        <asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" /> 
    </div> 
    </form> 
</body> 

4.     Add a javascript function to show a message box as shown below: 
<head runat="server"> 
    <title>Calling javascript function from code behind example</title> 
        <script type="text/javascript"> 
            function showDialogue() { 
                alert("this dialogue has been invoked through codebehind."); 
            } 
        </script> 
</head>
5.     Now double-click on the button and add the following code: 
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

6.     Run your project and click the Show Dialogue button

A message box will be displayed as shown below: 
screen shot of client side message box

0 comments:

Post a Comment

Sample Text

Muthukumar. Powered by Blogger.

About Me

My photo
Hi i am Muthu kumar,software engineer.