Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

AJAX Library

4.67/5 (49 votes)
31 May 2023CPOL4 min read 201.6K   4.5K  
.NET library to call server side method or API from JavaScript

Introduction

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:

Page_Load

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 six 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.
  6. Return Promise: Boolean value, it is used to return promise in place of callback and error method.

demoajaxapp/Methods.JPG

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:

Image 3

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:

Image 4

The Ajax DLL also supports Restful Service call. Note that it will call only those Restful Services which are in the 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 three 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

What is in the latest update? Support for MVC project. To use in MVC, it is easier than standard ASP.NET application, it does not require to add handler in web.config file. To use in MVC, you need to register controller with Html.AjaxScriptsFor method in View and call the method like this.

Image 5

Controller side just annotates method with Ajax.AjaxMethod attribute:

Image 6

Find the HTML code here:

ASP.NET
<%@ 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" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ajax Demo</title>

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

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

            function CallTest2()
            {
                var x = new Object();
                x.Name = "Mehul-Thakkar";
                x.Phone = 25460645;
                x.Email = "mehult@xyz.com";
                x.JoiningDate = "15-09-2010";
                _Default.PassClassObject(x);
            }
            function ReturnLength(obj)
            {
                alert(obj);
            }
            function Error_PassClassObject(obj)
            {
                alert(obj.ErrMsg);
            }

            function CallBack_ReturnArray(arrObj) {
            
                var Total=0;
                for(var i in arrObj)
                    Total+=parseInt(arrObj[i],10);
                    
                alert(Total);
            }
            function ReturnStrArray() {
                _Default.ReturnStrArray().then(function(arrObj) {
                    var str = '';
                    for (var i in arrObj)
                        str += arrObj[i] + "\n";

                    alert(str);
                });
            }
            function CallBack_ReturnObject(clsObj)
            {
                alert(clsObj.Email);
            }
            function CallBack_ReturnFArray(arrObj)
            {
                var Total=0;
                for(var i in arrObj)
                    Total+=parseFloat(arrObj[i],10);
                    
                alert(Total);
            }

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

            function ServiceCall() {
                SmartAjax.CallService(
                "http://localhost:2830/TestService.svc/GetData",
                '{ "value": "' + document.getElementById("txtServiceBox").value + '" }',
                { onSuccess: "serviceCallback", onError: "serviceError" }
                );
            }

            function serviceCallback(str) {
                alert(str);
            }

            function serviceError(str) {
                alert(str);
            }
                
    </script>
</head>
<body>
    <form id="form1" runat="server">
     <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div>
            <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">
                </div>
            </div>
            <br />
            <div style="border: solid 1px blue">
                Pass Array Object:
                <a href="#" onclick="CallTest1()">Click Here</a>
                <div id="Div1">
                </div>
            </div>
            <br />
            <div style="border: solid 1px green">
                Pass Class Object:
                <a href="#" onclick="CallTest2()">Click Here</a>
                <div id="Div2">
                </div>
            </div>
            <br />
            <div style="border: solid 1px orange">
                Return Array Object:
                <a href="#" onclick="_Default.ReturnArray()">Click Here</a>
                <div id="Div3">
                </div>
            </div>
            <br />
            <div style="border: solid 1px brown">
                Return String Array Object:
                <a href="#" onclick="ReturnStrArray()">Click Here</a>
                <div id="Div5">
                </div>
            </div>
            <br />
            <div style="border: solid 1px pink">
                Return Double Array Object:
                <a href="#" onclick="_Default.ReturnFArray()">Click Here</a>
                <div id="Div6">
                </div>
            </div>
            <br />
            <div style="border: solid 1px gray">
                Return Class Object:
                <a href="#" onclick="_Default.ReturnObject()">Click Here</a>
                <div id="Div4">
                </div>
            </div>
            <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">
                </div>
            </div>
            <br />
            <div style="border: solid 1px #aecfa5">
                Generic Support:
                <a href="#" onclick="_Default.GenericCollection()">Click Here</a>
                <div id="Div8">
                </div>
            </div>
            <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">
                </div>
            </div>
            <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>
            </div>
        </div>
       
        <asp:UpdatePanel runat="server" ID="UP1">
            <ContentTemplate>
                <asp:TextBox runat="server" ID="txt1">
                </asp:TextBox>
                <asp:Button runat="server" ID="b1" 
                 Text="click here" OnClick="b1_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Find the CS file code here:

C#
using System;
using System.Collections.Generic;
using System.Data;
using Ajax.NET;

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
    {
        [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();
            try
            {
                Adp.Fill(dt);
                if (dt.Rows.Count > 0)
                    return dt;
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        [AjaxMethod("PassArrayObject", "ReturnClassObject", null, "Loading...")]
        public Temp PassArrayObject(string[] str)
        {
            Temp t1 = new Temp();
            foreach (string st in str)
                t1.Name += st;

            return t1;
        }

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

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

        [AjaxMethod(false)]
        public string ReturnEvenOdd(int i)
        {
            if (i % 2 == 0)
                return "Number is Even";
            else
                return "Number is Odd";
        }

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

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

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

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

        [AjaxMethod]
        public Dictionary<string, Temp> GenericCollection()
        {
            return new Dictionary<string, Temp> { {"1", new Temp 
                   { Email = "test1@helo.com", Name = "test1", Phone = 1234567 }},
                   {"2", new Temp { Email = "test2@helo.com", 
                   Name = "test2", Phone = 21345 }}};
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Scripts.Add(this);
        }

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

Demo Project

Ajax.NET Library

History

  • 31st June, 2023: Article updated
  • 6th December, 2019: Article updated
    1. Framework upgrade
    2. Promise support
    3. MVC support
  • 30th July, 2014: Article updated
    1. Consecutive Ajax call support. Enable to make another Ajax call from success or error method of first Ajax call.
  • 20th July, 2013: Article updated
    1. More object oriented js
    2. Generic support
    3. Restful Service support
  • 9th July, 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

License

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