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

Simplifying Asp.Net Core Ajax

5.00/5 (5 votes)
12 Jul 2011CPOL3 min read 52.7K   403  
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)