Click here to Skip to main content
16,017,899 members
Articles / Web Development / ASP.NET
Tip/Trick

Simplifying Asp.Net Core Ajax

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
12 Jul 2011CPOL3 min read 52.6K   7   8
Walkthrough of Asp.Net Core Ajax

Introduction


This article demonstrates, how to implement Core Ajax in Asp.Net.

Background


What is Ajax?

Ajax is an acronym for Asynchronous JavaScript and XML.


In Asp.Net programming, in general concept of Ajax is to get/post data from/to Server using JavaScript or “Ajax Extension” controls.


What is Core Ajax?

In Asp.Net for “Server Controls”, we can easily apply Ajax using “Ajax Extension” controls like “UpdatePanel” and “ScripManager”.


On the other hand, what if we want to get/post data from/to Server using pure JavaScript.


This is achievable using “XMLHttpRequest” object. In below article we will see two ways of implementation of Core Ajax. Though we are not going to use pure “XMLHttpRequest” object code, but these mechanisms internally use “XMLHttpRequest” object only.


In fact every Ajax mechanism internally uses “XMLHttpRequest”.


Using the Code


1) Asp.Net Ajax using JQuery

[Please refer “JqueryExample.aspx” in attached code.]


Create new Asp.Net Project.


Add reference of “jquery-1.4.1.min.js” or ”jquery-1.5.1.min.js” in your .aspx page.


HTML
<head  runat="server">
<title>JQuery AJAX Example</title>

<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

</head>

Write JavaScript function "JqueryAjaxExample" to implement Ajax using JQuery.
HTML
<head  runat="server">
<title>JQuery AJAX Example</title>

<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

<script language="javascript" type="text/javascript" >
     
     function JqueryAjaxExample() {
         $.ajax({
            type: "GET",
            url: "JqueryExampleAjax.aspx",
            success: function (serverDate) {
                JqueryAjaxExampleResponse(serverDate);
            }
        });
    }

    function JqueryAjaxExampleResponse(serverDate) {
        alert(serverDate);
    }

</script>


</head>

In this function we have specified below settings.

“type” - Request is of type “GET”


“url” – URL to call server side execution is "JqueryExampleAjax.aspx"


“success” – JavaScript function which should execute after successful completion of this Ajax Request. We want JavaScript function “JqueryAjaxExampleResponse” should execute after successful completion of this Ajax Request.


Implementation of function “JqueryAjaxExampleResponse” is as below.


It will show alert of server date received from server side.


JavaScript
function JqueryAjaxExampleResponse(serverDate) {
        alert(serverDate);
    }

Now on Page Load of “JqueryExampleAjax.aspx” Page, write current system date to response.
C#
public partial class JqueryExampleAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Write(System.DateTime.Now.ToString());            
            Response.End();
        }
    }

Call function “JqueryAjaxExample” on click of some HTML input button.
HTML
<input id="btnServerTime" type="button" value="Show Server Time"  onclick="JqueryAjaxExample();" />

Let’s run the application and click on above HTML button.

This will show Date & Time of Server in alert message.


0.png

2) Asp.Net Ajax using “ICallbackEventHandler”


[Please refer “CallBackExample.aspx” in attached code.]


Let’s assume the scenario in which we want to trigger server side event of same page using JavaScript.


We can do this by using “ICallbackEventHandler” and JavaScript code.


Register the script on Page load, which will specify that JavaScript function “GetServerDate” will invoke event of server side. This will also register JavaScript function “GetServerResponseFunction” as a Call Back function.


C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

string registerCallBack = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetServerResponseFunction", "context");

                string registerCallBackscript;
registerCallBackscript = "function GetServerDate(arg, context)" + "{ " + registerCallBack + ";}";

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "GetServerTime", registerCallBackscript, true);
            }
        }

Now write JavaScript function “GetDateFromServer” which will call “GetServerDate”.

Function “GetServerDate” will call server side event.


JavaScript
function GetDateFromServer() {

            var dateFormat = '';

            if (document.getElementById("shortDate").checked) {
                dateFormat = 'shortDate';
            }
            else if (document.getElementById("longDate").checked) {
                dateFormat = 'longDate';
            }

            GetServerDate(dateFormat, '');
            
        }

Let’s declare and implement JavaScript function “GetServerResponseFunction”. This will simply alert the server date received from server side.
JavaScript
function GetServerResponseFunction(serverDate) {
          alert(serverDate);
      }

Implementation of “ICallbackEventHandler”

Now Inherit class of your page by interface “ICallbackEventHandler” as below.


C#
public partial class CallBackExample : System.Web.UI.Page, ICallbackEventHandler

Interface “ICallbackEventHandler” provides below events.
C#
public void RaiseCallbackEvent(string eventArgument)

private void GetCallbackResult(string format)

Event “RaiseCallbackEvent” will invoke from JavaScript function “GetServerDate”.

Event “GetCallbackResult” will invoke after event “RaiseCallbackEvent”. JavaScript function “GetServerResponseFunction” will invoke after this as a call back function.


Let’s do implementation of these events as below. “RaiseCallbackEvent” will set value of string variable “serverDateTime” based on eventArgument. This eventArgument contains argument value passed from JavaScript function “GetServerDate”.


Event “GetCallbackResult” will return value of string variable “serverDateTime” to Client side. This will be input for call back JavaScript function “GetServerResponseFunction”.


C#
string serverDateTime = "";

public void RaiseCallbackEvent(string eventArgument)
{
   if (eventArgument != null)
   {
     if (string.Compare(eventArgument, "shortDate") == 0)
      {
        serverDateTime = System.DateTime.Now.ToShortDateString();
      }
      else if (string.Compare(eventArgument, "longDate") == 0)
      {
        serverDateTime = System.DateTime.Now.ToLongDateString();
      }

   }
}

public string GetCallbackResult()
{
     return serverDateTime;
}

In aspx add two radio buttons for Format of the Date. Also add HTML input button to call JavaScript function “GetDateFromServer”.
HTML
Short Format:  <input id="shortDate" type="radio" checked="checked" name="DateFormat" style="width:20px;" />

Long Format:  <input id="longDate" type="radio" name="DateFormat" style="width:20px;"  />

   <input id="btnServerDate" type="button" value="Show Server Date"  onclick="GetDateFromServer();" />

Below diagram elaborates flow of function calls.

AspDotNetAjaxExample.png


Now run the application, select “Short Format” option and click on button.


Result will be as below.


1.png

Now select “Long Format” option and click on button.


Result will be as below.


2.png

Have a Happy Asp.Net Ajax Programming.

License

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


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
bbirajdar11-Oct-12 5:38
bbirajdar11-Oct-12 5:38 
GeneralRe: My vote of 5 Pin
RaisKazi11-Oct-12 5:50
RaisKazi11-Oct-12 5:50 
Thank you so much. Big Grin | :-D
Change is a pattern of life.

GeneralReason for my vote of 5 Excellent! Pin
Marcio_Coelho12-Dec-11 3:42
Marcio_Coelho12-Dec-11 3:42 
GeneralRe: Thank you so much Marcio. :) Pin
RaisKazi12-Dec-11 5:45
RaisKazi12-Dec-11 5:45 
GeneralReason for my vote of 5 Nice one, BTW came by Q/A section(Yo... Pin
thatraja6-Nov-11 21:39
professionalthatraja6-Nov-11 21:39 
GeneralRe: Thank you Raja. :) Pin
RaisKazi6-Nov-11 21:43
RaisKazi6-Nov-11 21:43 
GeneralIs this not excessive for a tip, and more suited to article? Pin
DaveAuld17-Jul-11 0:21
professionalDaveAuld17-Jul-11 0:21 
GeneralRe: Thanks Dave. Initially I wanted to Publish this as an Articl... Pin
RaisKazi17-Jul-11 3:00
RaisKazi17-Jul-11 3:00 

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.