Saturday, September 18, 2010

ASP.net - Call server side function in Javascript(Client Side)

You cannot call server-side code directly from client-side code because the server side code executes at server side and client side code at the client. So whenever we have to call serverside code from javascript, you will need to use AJAX.


Another option is that you can call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page.


The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

So let see how to call server side function into client side(javascript).

Step 1
Create a Web Application and give the solution name as SolServerSidetoClinetSide.

Step 2
Drag and drop two textbox in a page.In this example we will accepting the sring from the user in one textbox and display the string in another textbox. it is look like this


<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
        </asp:ScriptManager>
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
                <asp:TextBox ID="txtReturnName" runat="server"></asp:TextBox><br />    
                
                 
          </ContentTemplate> 
        </asp:UpdatePanel>     

Add the attribute EnablePageMethods="true" to the ScriptManager.

Step 3
Write a method,GetName Which will accept the string from the user and return the string.this method as a PageMethod and then call this method GetName from client side code by using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method.it is look like this


 /// <summary>
    /// Get the Name from the user
    /// </summary>
    /// <param name="Name">Specify the Name</param>
    /// <returns>String</returns>
    
    [System.Web.Services.WebMethod]
    public static String GetName(String Name)
    {
        try
        {
            return Name; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

Remember one thing page methods needs to be static in code behind.In short methods must be a static.

Step 4
Create a javascript for call server side code.Add a javascript file called Jscript.js to your solution (Right Click Project -> Add New Item -> Jscript File).it is look like this

function OnError(Result, txtReturnName) {
    try {
        alert(Result.get_message());
    }
    catch (E)
    { }
    
}

function OnComplete(Result, txtReturnName) {
    try {

        var _txtReturnName = document.getElementById(txtReturnName);
        _txtReturnName.value = Result;

        alert('Server side function sucessfully called'); 
    }
    catch (E)
   { }
}

function OnCall(txtName,txtReturnName) {

    try {
        var _txtName = document.getElementById(txtName);
        
        // Call Server Side Method
        PageMethods.GetName(_txtName.value, OnComplete, OnError, txtReturnName);
    }   
    catch (E)
    { }

}

Step 5
Create a reference of javascript file from aspx page and invoke the OnCall method whenever the textbox loses focus.it is look like this

<head runat="server">
    <title>Server Side to Client Side</title>

    <script language="javascript" type="text/javascript" src="JScript.js"></script> 
   
</head>

Step 6
To invoke the methods whenever the textbox looses focus, Create a CallJavaScript Method in code behind and call this method in a Page_Load Event,it is look like this
 /// <summary>
    /// Call JavaScript
    /// </summary>
    private void CallJavaScript()
    {
        try
        {
            txtName.Attributes.Add("OnBlur", "OnCall('" + txtName.ClientID + "','" + txtReturnName.ClientID + "');");   
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }


protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                CallJavaScript(); 
            }
        }
        catch (Exception)
        { }
    }

Full Code

1. .aspx Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Server Side to Client Side</title>

    <script language="javascript" type="text/javascript" src="JScript.js"></script> 
   
</head>
<body>

    
      
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
        </asp:ScriptManager>
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
                <asp:TextBox ID="txtReturnName" runat="server"></asp:TextBox><br />    
                
                 
          </ContentTemplate> 
        </asp:UpdatePanel>     
    </div>
    </form>
</body>
</html>

2. JScript.js

function OnError(Result, txtReturnName) {
    try {
        alert(Result.get_message());
    }
    catch (E)
    { }
    
}

function OnComplete(Result, txtReturnName) {
    try {

        var _txtReturnName = document.getElementById(txtReturnName);
        _txtReturnName.value = Result;

        alert('Server side function sucessfully called'); 
    }
    catch (E)
   { }
}

function OnCall(txtName,txtReturnName) {

    try {
        var _txtName = document.getElementById(txtName);
        
        // Call Server Side Method
        PageMethods.GetName(_txtName.value, OnComplete, OnError, txtReturnName);
    }   
    catch (E)
    { }

}

3. .aspx.cs (Code Behind)

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                CallJavaScript(); 
            }
        }
        catch (Exception)
        { }
    }

    #region Methods
    /// <summary>
    /// Get the Name from the user
    /// </summary>
    /// <param name="Name">Specify the Name</param>
    /// <returns>String</returns>
    
    [System.Web.Services.WebMethod]
    public static String GetName(String Name)
    {
        try
        {
            return Name; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    /// <summary>
    /// Call JavaScript
    /// </summary>
    private void CallJavaScript()
    {
        try
        {
            txtName.Attributes.Add("OnBlur", "OnCall('" + txtName.ClientID + "','" + txtReturnName.ClientID + "');");   
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Run the project.

Download
Download Source Code

No comments:

Post a Comment