Click here to Skip to main content
6,822,123 members and growing! (18,467 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » Libraries     Advanced License: The Code Project Open License (CPOL)

Ajax DLL

By Mehul M Thakkar

Library to call server side function from JavaScript
C#, .NET, ASP.NET, Ajax, Dev
Revision:15 (See All)
Posted:17 Nov 2009
Views:5,099
Bookmarked:30 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
9 votes for this article.
Popularity: 3.67 Rating: 3.84 out of 5
1 vote, 11.1%
1

2
2 votes, 22.2%
3
2 votes, 22.2%
4
4 votes, 44.4%
5

Introduction

Ajax DLL is an library developed by me using .NET 2005 for ASP.NET 2.0/3.0/3.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 an object.

In this given example, I have used the parameter as a string variable, an array object and a class object.

Using the Code

To work with Ajax.dll, you need to create a web application and a web site and add a reference of Ajax.dll which is in the attached file.

Once a DLL has been added into reference, you need to place a code on Page_Load event as below:

Page_Load

This way you can register your page in DLL with all your AJAX method[s], which are given in the image below. You need to add an attribute to the methods.

There are 5 optional parameters with the attribute:

  1. Method Name: A method which you want to call from JS. Default will be the execute method name which you have given.
  2. Js Callback method name: On Successful End Request of the AJAX. Default will be the Callback_<your method name>.
  3. Js Error method Name: If any Error at the time of End Request. Default will be the Error_<your method name>.
  4. Want to show some loading text: Bool flag to show a loading text or not. Default value is false.
  5. Loading Text: Which text you want to show. Default Text is string.Empty.
Methods.JPG

Once methods have been written, you need to call all these methods from JS. For that, you need to write JS methods as below:
Page_Load

Check here the CallTest1() function, from the function Test1 method is called as defined in the first parameter of AJAX attribute. The parameter value and the method name should be the same.

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

Also you need to add the extension .ajax and .ajaxj in your directory setting with ASP.NET API.

Find the HTML code here:

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" 
	Inherits="DemoAjaxApp._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>Ajax Demo</title>

    <script language="javascript" type="text/javascript">
			 
	function CallTest()
	{
		var id=document.getElementById('txtClientId').value;
		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";
			Test123(x);
		}
		function NameLength1(obj)
		{
		    alert(obj.Name);
		}
		function Error_Test1(obj)
		{
			alert(obj.ErrMsg);
		}
				
		function CallTest2()
		{
		    var x = new Object();
		    x.Name = "Mehul, Thakkar";
		    x.Phone = 25460645;
		    x.Email = "mehult@xyz.com";
			Test2(x);
		}
		function NameLength2(obj)
		{
		    alert(obj);
		}
		function Error_Test2(obj)
		{
			alert(obj.ErrMsg);
		}				
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <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">
                Array Object:
                <a href="#" onclick="CallTest1()">Click Here</a>
                <div id="Div1">
                </div>
            </div>
            <br />
            <div style="border: solid 1px green">
                Class Object:
                <a href="#" onclick="CallTest2()">Click Here</a>
                <div id="Div2">
                </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="TestSub()">Get Error</a>
            </div>
        </div>
    </form>
</body>
</html>

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;

namespace DemoAjaxApp
{
    public class Temp
    {
        string _name, _email;
        int _phone;

        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 partial class _Default : System.Web.UI.Page
    {
        [Ajax.AjaxMethod("Test", "NameLength", null, true, "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;
            }
        }

        [Ajax.AjaxMethod("Test123", "NameLength1", null, true, "Loading...")]
        public Temp Test1(string[] str)
        {
            Temp t1 = new Temp();
            foreach (string st in str)
                t1.Name += st;

            return t1;
        }

        [Ajax.AjaxMethod("Test2", "NameLength2", null, true, "Loading...")]
        public int Test2(Temp str)
        {
            return str.Name.Length;
        }

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

        protected void Page_Load(object sender, EventArgs e)
        {
            System.Web.UI.Page MyPage = this;
            Ajax.Utility.GenerateMethodScripts(this.GetType(), ref MyPage);

        }
    }
}

History

  • 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)

About the Author

Mehul M Thakkar


Member
Mehul Thakkar is having 7 yrs of experience in IT industry. He is having good command over Ms .Net and Ms Sql Server
Occupation: Team Leader
Location: India India

Other popular Ajax and Atlas articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
General.. Oky strange issue happening on a server set up .... Pinmembertridex3:05 4 Jan '10  
GeneralRe: .. Oky strange issue happening on a server set up .... PinmemberMehul M Thakkar18:55 4 Jan '10  
AnswerYou solution Described for server settings works perfectly!!! Pinmembertridex7:08 25 Nov '09  
GeneralThanks for the advice , will try it in a miomement... Pinmembertridex5:30 25 Nov '09  
GeneralMy vote of 1 PinmemberHoward Richards6:02 24 Nov '09  
GeneralRe: My vote of 1 PinmemberMehul M Thakkar19:07 24 Nov '09  
GeneralFantastic, butsmall problem.. Pinmembertridex2:37 23 Nov '09  
GeneralRe: Fantastic, butsmall problem.. PinmemberMehul M Thakkar19:01 23 Nov '09  
Generalmy 5 ! PinmemberJuraj Suchan8:17 19 Nov '09  
GeneralIntriguing PinmemberStephen Swensen18:21 17 Nov '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 17 Nov 2009
Editor: Deeksha Shenoy
Copyright 2009 by Mehul M Thakkar
Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project