Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to call Server Side function using ajax in asp.net

0.00/5 (No votes)
29 May 2008 1  
How to call Server Side function using ajax in asp.net

Introduction

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call server side code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.

Background

One option while using Microsoft ASP.NET AJAX is to 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. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
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.
Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.
I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead.

Using the code

Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.
Step 2: Drag and drop 1 labels and 2 textbox controls. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:
        <body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server">     
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
        <div>
        <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1 :"></asp:Label>
        <asp:TextBox ID="txtId" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />
        <br />
               <br />
             <br />
            </div>
    </form>
</body>
        

Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.

<connectionStrings>
        <remove name="all"/>
        <add name="NorthwindConnectionString" connectionString="Data Source=192.168.2.124;Initial Catalog=Northwind;User ID=sa;Password=sa"/>
    </connectionStrings>  

Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.

[System.Web.Services.WebMethod] public static string GetContactName(string custid) { if (custid == null || custid.Length == 0) return String.Empty; SqlConnection conn = null; try { string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString; conn = new SqlConnection(connection); string sql = "Select ContactName from Customers where CustomerId = @CustID"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("CustID", custid); conn.Open(); string contNm = Convert.ToString(cmd.ExecuteScalar()); return contNm; } catch (SqlException ex) { return "error"; } finally { conn.Close(); } }

Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}

At the same time, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>

Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.
function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
}
// set the destination textbox value with the ContactName
function CallSuccess(res, destCtrl)
{
var dest = document.getElementById(destCtrl);
dest.value = res;
}
// alert message on some failure
function CallFailed(res, destCtrl)
{
alert(res.get_message());
}
Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:
Add a reference to the javascript file in the body tag as shown below:
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
<form id="form1" runat="server">

Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event


 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtId.Attributes.Add("onblur", "javascript:CallMe('" + txtId.ClientID + "', '" + txtContact1.ClientID + "')");
        }
    } 
As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here