Click here to Skip to main content
12,552,478 members (27,394 online)
Click here to Skip to main content
Add your own
alternative version


120 bookmarked


, 30 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
.NET library to call server side method from JavaScript.


AJAX DLL is a library developed using .NET for ASP.NET 3.0/3.5/4.0/4.5. It is used to call server side methods from JavaScript. You can pass the method parameter value from JavaScript. A parameter can be a variable or a Model object.

In the given example, I have used the parameter as a string variable, an array object and a Model class object. A benefit of this DLL is that you can use it at UserControl level, so if you have some method in UserControl and you want to call it via JavaScript, you can achieve it using this DLL. A drawback of this DLL is that you cannot access your server control in your method, because the Page Life Cycle is not involved during the method call like in UpdatePanel. But you can access your server control from JavaScript and assign the value which will be returned by the AJAX method.

Using the Code   

It’s very simple to use Ajax DLL. You need to create a web application or a web site and add reference of Ajax.dll which is in the attached file.

Once a DLL has been added into your application, you need to place a line code in the Page_Load event as below:


This code will register your page class in DLL with all your AJAX method(s) written in the page class, which are given in the image below. Check the below image, you will find that the methods have been annotated with an attribute Ajax.AjaxMethod. You need to annotate with an attribute to the methods which you want to call from JavaScript.

There are five optional parameters with the Ajax.AjaxMethod attribute:

  1. Method name: A method which you want to call from JS. Default will be the same method name which you have created.
  2. Js callback method name: On Successful End Request of the AJAX call. Default will be the Callback_<your method name>.
  3. Js Error method Name: Any Error at the time of End Request of the AJAX call. Default will be the Error_<your method name>.
  4. Loading Text: The text you want to show. Default text is string.Empty.
  5. Asynchronous Call: Boolean value, used to make your call synchronous from JavaScript. Default value is True.


Once the methods have been written, you can call all these methods from JS as defined in the first parameter of Ajax.AjaxMethod. For that, you can write the JS methods as below: 

Check here the CallTest1() function. From the function, the PassArrayObject method is called as defined in the first parameter of the Ajax attribute. The parameter value and the method name should be the same. Also check the last function CallReturnEvenOdd() for which the callback method or error method is not required, because its server method ReturnEvenOdd is defined with the IsAsync=false parameter (check the previous image). So the value will be returned to the same function CallReturnEvenOdd(). _Default object is used to call the methods PassArrayObject and ReturnEvenOdd. This  _Default is nothing but the page class name.  So now we can create same name methods in page as well as in user control and call with respective class object.  

At last, you need to apply some configuration in the web.config file as below: 

The latest Ajax dll  supports Restful Service call. Note that it will call only those Restful Services which are in same domain. Steps to call Restful Service using this dll are given below. 

  1. Create Restful Service in your project.  
  2. Call using  SmartAjax.CallService method, which has 3 parameters.  
    1. URL: Restful service url  
    2. Method Parameters: Parameters in String Json format 
    3. Callback methods: 
      • onSuccess: A method name on successful call   
      • onError: A method name on error   


A complete example is given in attached demo project. 

 Find the HTML code here: 

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

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
<head runat="server">
    <title>Ajax Demo</title>

    <script language="javascript" type="text/javascript">
		function CallTest()
			var id=document.getElementById('txtClientId').value;
		function NameLength(obj)
			var i=0;
			var newdiv = document.getElementById('EmpData');
			newdiv.innerHTML = "";
			if(obj == null)
		        newdiv.innerHTML = "No Employee Found";
			mytable = document.createElement("table");
			mytable.cellSpacing = "0px"; = "1px solid #000";
			mytablebody = document.createElement("tbody");
			mycurrent_row = document.createElement("tr");
					mycurrent_cell = document.createElement("td");
					currenttext = document.createTextNode(obj.Rows[0].Columns[i].Name);
					mycurrent_cell.appendChild(currenttext); = "1px solid #000";
			for(var j=0;j<obj.RowCount;j++)
				var objRow = obj.Rows[j];
				mycurrent_row = document.createElement("tr");
					mycurrent_cell = document.createElement("td");
					if(objRow.Columns[i].Value != null)
						currenttext = document.createTextNode(objRow.Columns[i].Value + " ");
						currenttext = document.createTextNode(" ");
					mycurrent_cell.appendChild(currenttext); = "1px solid #000";
		function Error_Test(obj)
		function CallTest1()
		    var x = new Array();
		    x[0] = "Mehul";
		    x[1] = "Thakkar";
		function ReturnClassObject(obj)
		function Error_PassArrayObject(obj)

        function CallReturnEvenOdd() {
            var id = document.getElementById('txtNumber').value;
            var msg = _Default.ReturnEvenOdd(id);

		function CallTest2()
		    var x = new Object();
		    x.Name = "Mehul-Thakkar";
		    x.Phone = 25460645;
		    x.Email = "";
		    x.JoiningDate = "15-09-2010";
		function ReturnLength(obj)
		function Error_PassClassObject(obj)

		function CallBack_ReturnArray(arrObj) {
		    var Total=0;
		    for(var i in arrObj)
		function Error_ReturnArray(arrObj) {
		function CallBack_ReturnStrArray(arrObj)
		    var str='';
		    for(var i in arrObj)
		function CallBack_ReturnObject(clsObj)
	    function CallBack_ReturnFArray(arrObj)
		    var Total=0;
		    for(var i in arrObj)

	    function CallBack_GenericCollection(collObj) {
	        for (var item in collObj) {
	            alert("Name: " + collObj[item].Name + "\nPhone: " + 
	              collObj[item].Phone + "\nEmail: " + collObj[item].Email);

	    function ServiceCall() {
            '{ "value": "' + document.getElementById("txtServiceBox").value + '" }',
            { onSuccess: "serviceCallback", onError: "serviceError" }

	    function serviceCallback(str) {

	    function serviceError(str) {
    <form id="form1" runat="server">
     <asp:ScriptManager ID="ScriptManager1" runat="server">
            <div style="border: solid 1px yellow">
                Enter Emp No Here:
                <input type="text" id="txtClientId" />
                <a href="#" onclick="CallTest()">Retrieve Emp</a>
                <div id="EmpData">
            <br />
            <div style="border: solid 1px blue">
                Pass Array Object:
                <a href="#" onclick="CallTest1()">Click Here</a>
                <div id="Div1">
            <br />
            <div style="border: solid 1px green">
                Pass Class Object:
                <a href="#" onclick="CallTest2()">Click Here</a>
                <div id="Div2">
            <br />
            <div style="border: solid 1px orange">
                Return Array Object:
                <a href="#" onclick="_Default.ReturnArray()">Click Here</a>
                <div id="Div3">
            <br />
            <div style="border: solid 1px brown">
                Return String Array Object:
                <a href="#" onclick="_Default.ReturnStrArray()">Click Here</a>
                <div id="Div5">
            <br />
            <div style="border: solid 1px pink">
                Return Double Array Object:
                <a href="#" onclick="_Default.ReturnFArray()">Click Here</a>
                <div id="Div6">
            <br />
            <div style="border: solid 1px gray">
                Return Class Object:
                <a href="#" onclick="_Default.ReturnObject()">Click Here</a>
                <div id="Div4">
            <br />
            <div style="border: solid 1px silver">
                Synchronous Call using AJAX:
                <input type="text" id="txtNumber" />
                <a href="#" onclick="CallReturnEvenOdd()">Click Here</a>
                <div id="Div7">
            <br />
            <div style="border: solid 1px #aecfa5">
                Generic Support:
                <a href="#" onclick="_Default.GenericCollection()">Click Here</a>
                <div id="Div8">
            <br />
            <div style="border: solid 1px #2ec2d7">
                Restful Service Call:
                <input type="text" id="txtServiceBox" />
                <a href="#" onclick="ServiceCall()">Click Here</a>
                <div id="Div9">
            <br />
            <div style="border: solid 1px red">
            Access this textbox from Ajax dll
            <asp:TextBox runat="server" ID="txt"></asp:TextBox>
            <a href="#" onclick="_Default.ControlAccess()">Get Error</a>
        <asp:UpdatePanel runat="server" ID="UP1">
                <asp:TextBox runat="server" ID="txt1">
                <asp:Button runat="server" ID="b1" 
                       Text="click here" OnClick="b1_Click" />

Find the CS file code here:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace DemoAjaxApp

    public class Temp
        string _name, _email;
        int _phone;
        DateTime _doj;

        public string Name { get { return _name; } set { _name = value; } }
        public int Phone { get { return _phone; } set { _phone = value; } }
        public string Email { get { return _email; } set { _email = value; } }
        public DateTime JoiningDate{ get {return _doj;} set{ _doj = value;}}

    public partial class _Default : System.Web.UI.Page
        [Ajax.AjaxMethod("Test", "NameLength", null, "Loading...")]
        public DataTable Test(string Id)
            System.Data.SqlClient.SqlConnection con = 
              new System.Data.SqlClient.SqlConnection("server=mehult;Database=mehul;User Id=sa;Password=");
            System.Data.SqlClient.SqlDataAdapter Adp = 
              new System.Data.SqlClient.SqlDataAdapter("Select * from emp where no=" + Id, con);

            DataTable dt = new DataTable();
                if (dt.Rows.Count > 0)
                    return dt;
                    return null;
            catch (Exception ex)
                return null;
          "ReturnClassObject", null, "Loading...")]
        public Temp PassArrayObject(string[] str)
            Temp t1 = new Temp();
            foreach (string st in str)
                t1.Name += st;

            return t1;

          "ReturnLength", null, "Loading...")]
        public int PassClassObject(Temp str)
            return str.Name.Length;

        [Ajax.AjaxMethod("ControlAccess", false, false, "Loading...")]
        public void ControlAccess(string str)
            txt.Text = str;

        public string ReturnEvenOdd(int i)
            if (i % 2 == 0)
                return "Number is Even";
                return "Number is Odd";

        [Ajax.AjaxMethod(null, true, false, "Loading...")]
        public int[] ReturnArray()
            int[] i ={ 1, 2, 3, 4 };
            return i;

        public string[] ReturnStrArray()
            string[] str ={ "\\'1\\'", "2", "3", "4" };
            return str;

        [Ajax.AjaxMethod(null, true, false, "Loading...")]
        public double[] ReturnFArray()
            double[] i ={ 1.423, 2.543, 3.765, 4.65 };
            return i;

        [Ajax.AjaxMethod(null, true, false, null)]
        public Temp ReturnObject()
            Temp obj = new Temp();
            obj.Name = "hello";
            obj.Phone = 420840;
            obj.Email = "";
            return obj;

        public Dictionary<string, Temp> GenericCollection()
            return new Dictionary<string, Temp> { {"1", 
              new Temp { Email = "", Name = "test1", Phone = 1234567 }},
             {"2", new Temp { Email = "", Name = "test2", Phone = 21345 }}};

        protected void Page_Load(object sender, EventArgs e)

        protected void b1_Click(object sender, EventArgs e)
            txt1.Text = "hello";


  • 30th Jul 2014: Article updated. 
    1. Consecutive ajax call support. Enable to make another ajax call from success or error method of first ajax call.
  • 20th Jul 2013: Article updated. 
    1. More object oriented js.
    2. Generic support. 
    3. Restful Service support.  
  • 9th Jul, 2011: Article updated.
    1. No need to add extensions "ajax" & "ajaxj" in IIS.
    2. ShowLoading parameter is removed. If you don't want to display loading message, pass string.empty or null.
    3. New Parameter IsAsync is introduced, default value is true. If false, then it will make synchronize call from JavaScript. No Callback or Error method is required to handle it.
    4. Less JS rendering. Performance is improved.
  • 9th February, 2010: Article updated.
  • 17th November, 2009: Initial post.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mehul M Thakkar
Technical Lead
India India
Mehul Thakkar is having 8 yrs of experience in IT industry. He is having good command over Ms .Net and Ms Sql Server

You may also be interested in...


Comments and Discussions

QuestionUseless without... Pin
Dewey5-Aug-16 6:16
memberDewey5-Aug-16 6:16 
QuestionGood Work Pin
VDKK21-Mar-16 19:53
memberVDKK21-Mar-16 19:53 
QuestionHelp needed on iis7 with Dot net 4.0 Pin
sudipta.tripathy11-Mar-15 19:04
membersudipta.tripathy11-Mar-15 19:04 
AnswerRe: Help needed on iis7 with Dot net 4.0 Pin
Mehul M Thakkar16-Mar-15 2:55
memberMehul M Thakkar16-Mar-15 2:55 
GeneralRe: Help needed on iis7 with Dot net 4.0 Pin
sudipta.tripathy18-Mar-15 13:55
membersudipta.tripathy18-Mar-15 13:55 
GeneralRe: Help needed on iis7 with Dot net 4.0 Pin
Mehul M Thakkar23-Mar-15 20:34
memberMehul M Thakkar23-Mar-15 20:34 
QuestionNested Ajax Calls Pin
pyarli17-May-14 5:58
memberpyarli17-May-14 5:58 
AnswerRe: Nested Ajax Calls Pin
Mehul M Thakkar19-Jun-14 3:21
memberMehul M Thakkar19-Jun-14 3:21 
GeneralRe: Nested Ajax Calls Pin
pyarli24-Jun-14 7:47
memberpyarli24-Jun-14 7:47 
GeneralRe: Nested Ajax Calls Pin
pyarli27-Jun-14 18:05
memberpyarli27-Jun-14 18:05 
GeneralRe: Nested Ajax Calls Pin
Mehul M Thakkar30-Jun-14 3:10
memberMehul M Thakkar30-Jun-14 3:10 
GeneralRe: Nested Ajax Calls Pin
pyarli7-Jul-14 10:16
memberpyarli7-Jul-14 10:16 
GeneralRe: Nested Ajax Calls Pin
pyarli23-Jul-14 17:41
memberpyarli23-Jul-14 17:41 
GeneralRe: Nested Ajax Calls Pin
Mehul M Thakkar23-Jul-14 21:09
memberMehul M Thakkar23-Jul-14 21:09 
GeneralRe: Nested Ajax Calls Pin
pyarli24-Jul-14 10:37
memberpyarli24-Jul-14 10:37 
GeneralRe: Nested Ajax Calls Pin
pyarli29-Jul-14 8:26
memberpyarli29-Jul-14 8:26 
GeneralRe: Nested Ajax Calls Pin
Mehul M Thakkar30-Jul-14 5:29
memberMehul M Thakkar30-Jul-14 5:29 
GeneralRe: Nested Ajax Calls Pin
pyarli31-Jul-14 9:02
memberpyarli31-Jul-14 9:02 
QuestionAccesss to Session Variable Pin
pyarli9-Dec-13 9:39
memberpyarli9-Dec-13 9:39 
AnswerRe: Accesss to Session Variable Pin
Mehul M Thakkar10-Dec-13 20:46
memberMehul M Thakkar10-Dec-13 20:46 
GeneralRe: Accesss to Session Variable Pin
pyarli13-Dec-13 4:28
memberpyarli13-Dec-13 4:28 
GeneralRe: Accesss to Session Variable Pin
Mehul M Thakkar15-Dec-13 18:42
memberMehul M Thakkar15-Dec-13 18:42 
GeneralRe: Accesss to Session Variable Pin
pyarli16-Dec-13 3:44
memberpyarli16-Dec-13 3:44 
GeneralRe: Accesss to Session Variable Pin
Mehul M Thakkar16-Dec-13 6:04
memberMehul M Thakkar16-Dec-13 6:04 
QuestionCould you compare this approach to one using jQuery and Ajax calls? Pin
ahagel28-Aug-13 18:05
memberahagel28-Aug-13 18:05 
AnswerRe: Could you compare this approach to one using jQuery and Ajax calls? Pin
Mehul M Thakkar17-Oct-13 23:20
memberMehul M Thakkar17-Oct-13 23:20 
GeneralMy vote of 5 Pin
raj ch23-Aug-13 21:54
memberraj ch23-Aug-13 21:54 
GeneralMy vote of 5 Pin
Shivarajbk10-Jun-13 19:49
memberShivarajbk10-Jun-13 19:49 
QuestionWhich one is better? Pin
Shivarajbk10-Jun-13 19:43
memberShivarajbk10-Jun-13 19:43 
AnswerRe: Which one is better? Pin
Mehul M Thakkar11-Jun-13 3:26
memberMehul M Thakkar11-Jun-13 3:26 
GeneralRe: Which one is better? Pin
Shivarajbk11-Jun-13 21:10
memberShivarajbk11-Jun-13 21:10 
Questionwhere Can I get source file of Ajax.dll ? Pin
Toater26-Apr-13 19:22
memberToater26-Apr-13 19:22 
QuestionNice Attempt Pin
Prasad Khandekar16-Apr-13 0:01
memberPrasad Khandekar16-Apr-13 0:01 
AnswerRe: Nice Attempt Pin
Dana Cobb14-May-13 6:42
memberDana Cobb14-May-13 6:42 
AnswerRe: Nice Attempt Pin
Jasmine250114-May-13 7:16
memberJasmine250114-May-13 7:16 
GeneralRe: Nice Attempt Pin
Mehul M Thakkar17-Dec-13 2:11
memberMehul M Thakkar17-Dec-13 2:11 Frame work 3.5 not suppotred Pin
AJMAL SHAHZAD4-Apr-13 20:01
memberAJMAL SHAHZAD4-Apr-13 20:01 
GeneralRe: .net Frame work 3.5 not suppotred Pin
Toater26-Apr-13 19:26
memberToater26-Apr-13 19:26 
GeneralMy vote of 5 Pin
AJMAL SHAHZAD4-Apr-13 19:12
memberAJMAL SHAHZAD4-Apr-13 19:12 
GeneralRe: My vote of 5 Pin
Mehul M Thakkar4-Apr-13 19:28
memberMehul M Thakkar4-Apr-13 19:28 
QuestionWebMethod Pin
Andrei Bozantan15-Jul-11 2:11
memberAndrei Bozantan15-Jul-11 2:11 
AnswerRe: WebMethod [modified] Pin
Mehul M Thakkar15-Jul-11 22:07
memberMehul M Thakkar15-Jul-11 22:07 
QuestionNice effort Pin
Pranay Rana14-Jul-11 19:26
memberPranay Rana14-Jul-11 19:26 
GeneralIIS 7 and Ajax.dll Pin
blablablalolrawr13-Apr-11 2:12
memberblablablalolrawr13-Apr-11 2:12 
General'Ajax.Utility' does not contain a definition for 'GenerateMethodScripts' Pin
Member 433557716-Jun-10 2:30
memberMember 433557716-Jun-10 2:30 
GeneralRe: 'Ajax.Utility' does not contain a definition for 'GenerateMethodScripts' Pin
Mehul M Thakkar20-Jun-10 18:43
memberMehul M Thakkar20-Jun-10 18:43 
GeneralRe: 'Ajax.Utility' does not contain a definition for 'GenerateMethodScripts' Pin
Member 37653577-Jul-10 4:56
memberMember 37653577-Jul-10 4:56 
GeneralRe: 'Ajax.Utility' does not contain a definition for 'GenerateMethodScripts' Pin
Mehul M Thakkar7-Jul-10 18:55
memberMehul M Thakkar7-Jul-10 18:55 
GeneralRe: 'Ajax.Utility' does not contain a definition for 'GenerateMethodScripts' Pin
Member 37653578-Jul-10 3:38
memberMember 37653578-Jul-10 3:38 
GeneralRe: 'Ajax.Utility' does not contain a definition for 'GenerateMethodScripts' Pin
Mehul M Thakkar8-Jul-10 18:29
memberMehul M Thakkar8-Jul-10 18:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161021.1 | Last Updated 30 Jul 2014
Article Copyright 2009 by Mehul M Thakkar
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid