Tuesday, June 18, 2013

Calling javascript function from CodeBehind with C#

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
  7. A message box will be displayed as shown below:
    screen shot of client side message box

No comments:

Post a Comment