Twitter Feed Popout byInfofru

Show Loading Message in Asp.net AJAX

In this post, I will explain you how can we show Loading message in asp.net ajax without using Update Progress. Now some one may asked, why do I want to skip Update Progress ?

Well, there can be several reasons for this, fist of all you have to work on every single page, and on every update panel to get the update progress working.

There are basically three methods of meeting this requirement.

  1. Using Master Pages : A very smart way, but not all of us are using them .. right ?
  2. Extending Page Class  : A little harder but to me it is very elegant way.
  3. Extending Script Manager : Similar to the page class one, but implementation is comparatively simple.

The Basics:

Before I start with exploring the different approaches let me first create a ground by showing what things will be involve in creating a loading message.

I want the background to be grayed and displayed a simple loading text at the top, for that we need a style sheet, which will apply to the loading message div.  Create a stylesheet and call it style.css

.ModalProgressContainer
{
    z-index: 10005;
    position: fixed;
    cursor: wait; 
    top:0%; 
    background-color: #ffffff; 
    filter: alpha(opacity=50);
    opacity: 0.5;
    -moz-opacity: .5; 
    height: 100%;
    width: 100%;
    text-align: center; 
    
    } 
.ModalProgressContent
{
    padding: 10px; 
    border: solid 0px #000040; 
    font-weight: bold; 
    background-color:#ffffff;
    margin-top:300px;
} 

Now lets read and understand the following script.

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

// ----------------------------- //
// the below script will be saved in JS File, create a JS file and call it ajaxload.js and save the following script

function InitializeRequest(sender, args) {

    if (document.getElementById('ProgressDiv') != null)
       $get('ProgressDiv').style.display = 'block';
    else
        createContorl();
}

function EndRequest(sender, args) {

    if (document.getElementById('ProgressDiv') != null)
        $get('ProgressDiv').style.display = 'none';
    else
        createContorl();
}

function createContorl() {
    var parentDiv = document.createElement("div");
    parentDiv.setAttribute("class", "ModalProgressContainer");
    parentDiv.setAttribute("Id", "ProgressDiv");
 

    var innerContent = document.createElement("div");
    innerContent.setAttribute("class", "ModalProgressContent");
    var img = document.createElement("img");

    img.setAttribute("src", "/Images/Images/Loading.gif");

    var textDiv = document.createElement("div");
    textDiv.innerHTML = 'Loading....';

    innerContent.appendChild(img);
    innerContent.appendChild(textDiv);

    parentDiv.appendChild(innerContent);

    document.body.appendChild(parentDiv);

}

Notice,in the first three lines. We are getting the instance of PageRequestManager and then defining InitilizeRequest and EndRequest functions to display or hide the loading div. Where as, in createControl function we are simply writing DHTML, to be more specific there is no HTML of the loading div in our markup. So, we are writing that from JavaScript.

Also, note the that I have break down this script into two part by using comments. First is the declaration and second is definition of the functions.

note: The definition will take place on a seperate JS file where as the declaration need to be made in the page, under body markup.  Now we are all set to explore different approaches.

 

Using Master Pages :

A very simple approach, all you need to do is open your master page and paste the following lines in the head section.

<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="ajaxload.js"></script>

 

And in body, after form tag create a script section and paste the following JavaScript.

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

 

Notice it is the same declaration section which we have discussed above and that’s it you are done. All the content form of your web application should now display loading div on each partial postback.

 

Extending Page Class  :

For this, create a class file and call it ajaxPage and inherit it from System.Web.UI.Page and write the following code.

public class ajaxPage : Page
{
    protected override void OnLoad(EventArgs e)
    {
        //Include CSS File
        Page.Header.Controls.Add(new LiteralControl("<link href='style.css' rel='stylesheet' type='text/css' />"));


        //Include JS file on the page
        ClientScript.RegisterClientScriptInclude("ajaxload", ResolveUrl("~/ajaxload.js"));

        //Writing declaration script 
        String script = "var prm = Sys.WebForms.PageRequestManager.getInstance();";
        script += "prm.add_initializeRequest(InitializeRequest);";
        script += "prm.add_endRequest(EndRequest);";

        ClientScript.RegisterStartupScript(typeof(string), "body", script, true);

        base.OnLoad(e);
    }

}

 

Well, we have simply extend the System.Web.UI.Page into our own class and override OnLoad function to include the JS file and write the declaration markup.

Now, on the page code behind where you want to implement Loading message change the inherit namespace from System.Web.UI.Page to ajaxPage (make sure you namespace).

 

Extending Script Manager :

Now instead of extending page class we will extend Script Manager control and for that create a new class file and call it ScrtipManagerExt and write the following code.

public class ScriptManagerExt : ScriptManager
{
    protected override void OnLoad(EventArgs e)
    {

        //Include CSS File
        Page.Header.Controls.Add(new LiteralControl("<link href='style.css' rel='stylesheet' type='text/css' />"));

        RegisterClientScriptInclude(this, typeof(Page), "ajaload", ResolveClientUrl("~/ajaxload.js"));

        String script = "var prm = Sys.WebForms.PageRequestManager.getInstance();";
        script += "prm.add_initializeRequest(InitializeRequest);";
        script += "prm.add_endRequest(EndRequest);";

        RegisterStartupScript(this, typeof(Page), "ajaxtest", script, true);
        base.OnLoad(e);
    }
}

Almost the same thing we did in extend page approach, only the implementation will be change. Instead of using the old Script Manager we will use our new one. the include directive and markup will look like as below.

<%@ Register Assembly="Assembly" Namespace="namespace" TagPrefix="cc1" %>
<cc1:ScriptManagerExt ID="ScriptManagerExt1" runat="server">
</cc1:ScriptManagerExt>

 

That’s it we are done. I tried to make it simpler and show you every possible way I know of doing this task. Again, any approach selection will be on you and your project type. You can also download  the VS 2008 project file.

How to show and select month/year in Calendar Extender

In this post I will explain you, How to make calendar extender control to show month / year view by default and instead of selecting dates how can we use calendar extender to select months.

Before I start, let me say that I got extensive support from this forum post http://forums.asp.net/t/1349086.aspx. Thanks to Zhi-Qiang Ni, but the way he follow was a little bit lengthy. However, all credit still goes to him because I gain the exact idea from his post.

Let me start by creating a calendar extender control and attach it to a textbox.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" OnClientHidden="onCalendarHidden"  OnClientShown="onCalendarShown" BehaviorID="calendar1"
    Enabled="True" TargetControlID="TextBox1">
</cc1:CalendarExtender>


Now, in extender markup, notice onClientHidden and OnClientShown event which I implemented as below.

function onCalendarShown() {
 
     var cal = $find("calendar1");
     //Setting the default mode to month
     cal._switchMode("months", true);
     
     //Iterate every month Item and attach click event to it
     if (cal._monthsBody) {
         for (var i = 0; i < cal._monthsBody.rows.length; i++) {
             var row = cal._monthsBody.rows[i];
             for (var j = 0; j < row.cells.length; j++) {
                 Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
             }
         }
     }
 }
 
 function onCalendarHidden() 
 {
     var cal = $find("calendar1");
     //Iterate every month Item and remove click event from it
       if (cal._monthsBody) {
         for (var i = 0; i < cal._monthsBody.rows.length; i++) {
             var row = cal._monthsBody.rows[i];
             for (var j = 0; j < row.cells.length; j++) {
                 Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild,"click",call);
             }
         }
     }
 
 }

Pretty simple, In onCalendarShown method I just set the default mode to month and then iterate the control to get month item and attach on click event to it. So that, it will not go further to show us dates of that month and select the first day of that month instead.

Where as, In onCalendarHidden I am simply detaching the click event from month items. Now notice the last parameter of Sys.UI.DomEvent.addHandler function, it is the name of the function which will do the rest of the magic as below.

function call(eventElement)
        {
            var target = eventElement.target;
            switch (target.mode) {
            case "month":
                var cal = $find("calendar1");
                cal._visibleDate = target.date;
                cal.set_selectedDate(target.date);
                cal._switchMonth(target.date);
                cal._blur.post(true);
                cal.raiseDateSelectionChanged();
                break;
            }
        }

Here we are simply selecting the month as the selected date of calendar control. and finally the control will look like as below.

cal_extender

You can get the source code from here :
http://cid-cdbfe38dc780f729.skydrive.live.com/self.aspx/.Public/Calendar%20Extender%20Month.zip

Datatable to JSON

In this post I will explain you, how can we serialize Datatable to JSON. So that, it can easily pass to JavaScript to get the AJAX done.

First of all fill a Datatable with some results.

DataTable dt = new DataTable();
 
SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ToString());
objSqlCon.Open();
 
SqlDataAdapter objSqlDa = new SqlDataAdapter("select * from Production.Product", objSqlCon);
 
objSqlDa.Fill(dt);

Now create a String Builder object that will contain the JSON text and JavascriptSerializer which will serialize the output in JSON.

StringBuilder objSb = new StringBuilder();
JavaScriptSerializer objSer = new JavaScriptSerializer();

Now here we are going to iterate each row and column of data table and put all of them in Dictionary

Dictionary<string, object> resultMain = new Dictionary<string, object>();
int index = 0;
 
foreach (DataRow dr in dt.Rows)
{
    Dictionary<string, object> result = new Dictionary<string, object>();
 
    foreach (DataColumn dc in dt.Columns)
    {
        result.Add(dc.ColumnName, dr[dc].ToString());
    }
    resultMain.Add(index.ToString(), result);
    index++;
}

Notice that, I have created a new dictionary object for every row and finally put all of the dictionaries in Another dictionary I.E. resultMain.

In the end, I have simply Serialize the resultMain Dictionary to render JSON.

A complete post of utilizing Datatable  in JavaScript through AJAX is in the process, I will post that soon.

Passing Parameter To User Control On A Modal Popup

This is the most demanded scenario for the one who are using Asp.net AJAX Control Toolkit, I mean I have seen most of the people asking for this feature on asp.net forum.

Unfortunately, we have no such functionality provided in Modal Popup because the control get rendered once the page is loaded and the Modal Popup is just a JavaScript which work is just to display a div which is hidden.

Here is a little work around for those who wants to pass parameter to user control using Modal Popup. Basically, the idea is to keep the user control in a separate page and call that page using JavaScript and put the response on the a Modal Popup Div.

Remember, as this is only a JavaScript we need to set the parameter using JavaScript or we need to save the parameters on Page_Load in any Hidden field and access that later from JavaScript.

To start, I have created two pages and a user control following is the naming stuff for them

  1. Default.aspx (Contains Modal Popup)
  2. ControlCaller.aspx  (Contains User Control)
  3. Controls.ascx (User Control)

Default.aspx page html will look like as follows

   1: <form id="form1" runat="server">
   2:     <div>
   3:     
   4:         <asp:ScriptManager ID="ScriptManager1" runat="server">
   5:         </asp:ScriptManager>
   6:         <asp:Button ID="Button1" runat="server" Text="Show Popup" OnClientClick="setupParam()" />
   7:     
   8:     </div>
   9:     <cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="pnlControl" TargetControlID="Button1">
  10:     </cc1:ModalPopupExtender>
  11:     <asp:Panel ID="pnlControl" runat="server">
  12:             
  13:     </asp:Panel>
  14:     
  15:     <asp:HiddenField ID="hf_username" runat="server" />
  16:     <asp:HiddenField ID="hf_password" runat="server" />
  17:     <asp:HiddenField ID="hf_registredDate" runat="server" />
  18:     
  19:     </form>

Keep in mind that the three hidden fields I have taken here are for the Parameters.

Now Let's see what we have in ControlCaller.aspx

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ControlCaller.aspx.cs" Inherits="LearnWebApp.ControlCaller" %>
   2: <%@ Register src="Controls/Control.ascx" tagname="Control" tagprefix="uc1" %>
   3:     <uc1:Control ID="Control1" runat="server" />

Just user control implementation and nothing else. Please make sure to remove all the head, html and form tags.

Following is the html of Control.ascx

   1: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Control.ascx.cs" Inherits="LearnWebApp.Controls.Control" %>
   2: User Name :
   3: <asp:Label ID="lblUserID" runat="server" Text="Label"></asp:Label>
   4: <br />
   5: Registered Date :
   6: <asp:Label ID="lblDate" runat="server" Text="Label"></asp:Label>
   7: <br />
   8: Password:
   9: <asp:Label ID="lblPassword" runat="server" Text="Label"></asp:Label>

And here is the code behind of the Control

   1: private string _userName;
   2:         private string _RegisteredDate;
   3:         private string _Password;
   4:  
   5:         public string userName
   6:         {
   7:             get { return _userName; }
   8:             set { _userName = value; }
   9:         }
  10:         public string RegisteredDate
  11:         {
  12:             get { return _RegisteredDate; }
  13:             set { _RegisteredDate = value; }
  14:         }
  15:         public string Password
  16:         {
  17:             get { return _Password; }
  18:             set { _Password = value; }
  19:         }
  20:         protected void Page_Load(object sender, EventArgs e)
  21:         {
  22:             if (!Page.IsPostBack) 
  23:             {
  24:                 lblDate.Text = _RegisteredDate;
  25:                 lblPassword.Text = _Password;
  26:                 lblUserID.Text = _userName;
  27:             }
  28:         }

Please bear in mind, that the properties we have taken here are for the parameters as you can see I am also setting these properties on label at Page_Load.

and here we have the script which we need to add on the default.aspx head section

   1: <script language="javascript">
   2:     var request = false;
   3:        try {
   4:          request = new XMLHttpRequest();
   5:        } catch (trymicrosoft) {
   6:          try {
   7:            request = new ActiveXObject("Msxml2.XMLHTTP");
   8:          } catch (othermicrosoft) {
   9:            try {
  10:              request = new ActiveXObject("Microsoft.XMLHTTP");
  11:            } catch (failed) {
  12:              request = false;
  13:            }  
  14:          }
  15:        }
  16:        
  17:       function GetResult() {
  18:         var divComm = document.getElementById('pnlControl');
  19:         divComm.innerHTML = "Please wait processing your request!!!";
  20:         var rnd = Math.random() * 1000000;
  21:         var url = 'ControlCaller.aspx?userName=' +document.getElementById("hf_username").value + "&password=" + document.getElementById("hf_password").value  + "&Date="+ document.getElementById("hf_registredDate").value  +'&rnd=' + rnd;
  22:         request.open("GET", url, true);
  23:         request.onreadystatechange = GetResultComplete;
  24:         request.send(null);
  25:     }
  26:     function GetResultComplete() {
  27:         if (request.readyState == 4) {
  28:             //alert(request.responseText);
  29:             if (request.status == 200) {
  30:                 var divComm = document.getElementById('pnlControl');
  31:                 if (divComm) {
  32:                     divComm.innerHTML = request.responseText;
  33:                 }
  34:             }
  35:         }
  36:     }
  37:     function setupParam()
  38:         {
  39:             document.getElementById("hf_username").value = "User is for test !!!";
  40:             document.getElementById("hf_password").value  = "testing.....";
  41:             document.getElementById("hf_registredDate").value  = "10/04/84";
  42:             GetResult();
  43:             
  44:         }
  45:     </script>

Notice the setupParam() function, we are setting our parameter here and then call the GetResult function which is making an AJAX call to the page we have created. That's it by using this method we can have parameterized user control inside Modal Popup.

You can download the full Visual Studio 2008 Project from here.

Disable Control When Asp.net AJAX is in progress

If the AJAX call to the server take too much time, then there is a possibility that user might press some other buttons or some other event occurred which will cause your AJAX call to stop and make a new request.

To overcome this situation, I decided to have div on the top of the page so that while AJAX call is in progress user cannot do any thing else.

So I simply Drag and Drop a Update Progress Control and write the following stuff.

<asp:UpdateProgress ID="UpdateProgress1" runat="server">
    <ProgressTemplate>
        <div id="Progress">Please wait ......</div>
       <div id="bgDiv"></div> 
    </ProgressTemplate>
</asp:UpdateProgress>

And add the following style on head section of the page.

   1: <style>
   2:     #bgDiv {
   3:       position:absolute;
   4:       top:0px;
   5:       bottom:0px;
   6:       left:0px;
   7:       right:0px;
   8:       overflow:hidden;
   9:       padding:0;
  10:       margin:0;
  11:       background-color:black; 
  12:       filter:alpha(opacity=50);
  13:       opacity:0.5;
  14:       z-index:500;
  15:     }
  16:     #Progress
  17:     {
  18:         position: absolute;
  19:         background-color:Red;
  20:         width: 300px;
  21:         z-index: 600;
  22:     }
  23:  
  24:  
  25:     </style>

There we go whenever AJAX call made, a background div will appear and on top of that we have our message "Please wait"

Here is the snapshot

image

Long Waited Task in Asp.net

Yesterday, one my my friend ask me a query about sending some 500+ emails using an asp.net page. Sending bulk email using asp.net is obviously an issue. I mean, You cannot keep the page on the post back state for the five minutes. Your page will get expired and even if you increase the Request Timeout period it is still not a good approach.So for that, There are couple of approaches like1. You can have a table in which you store all the emails and create a Windows Service or Schedule Task to read tables of send emails accordingly.2. Open a thread on the server side using delegate and return the page to the browser and show the progress using Asynchronous operation.Ā As We were operating on shared hosting first approach doesn't seem fruitful for us. So, we decided to go with the second approach and for that we use delegates. Let me show you step by step.
1: Public Delegate Sub LongTimeTask_Delegate()2: Private fileName as String
Here I have declared a delegate and a global variable called filename which I will use for getting the status of the process.Now on the click event of my button which start the process. I have write the following code
1: Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click2: Dim rnd As Double = New Random().Next()3: fileName = Session.SessionID & "_" & rnd & ".txt"4: Dim d As LongTimeTask_Delegate5: d = New LongTimeTask_Delegate(AddressOf LongTimeTask)6:Ā  7: Dim R As IAsyncResult8: 9: R = d.BeginInvoke(New AsyncCallback(AddressOf TaskCompleted),nothing)10: Dim strScript As String = "<script language='javascript'> setInterval('GetResult(""" + fileName + """)',2000); </script>"11:Ā  12: Button1.Enabled= False13: Response.Write(strScript) 'TODO : Can take write on literal14: End Sub
On line no 3, I am setting filename variable to the session id and a random numberOn line no 4, Declare and Initialize Delegate and passed a function that will be executed by DelegateOn line no 7 and on, We invoke the delegate and store the result in IAsyncResult and also specify the function that will execute once the delegate is complete.On line no 10, we are writing a script on the page which is there to show us the status of process timely.Now, lets come LongTimeTask function, in which we have the whole stuff.
1: Public Sub LongTimeTask()2: Dim totCount As Integer = 5003: For a As Integer = 1 to totCount4: Try5: If Not File.Exists(fileName)6: File.Create(fileName)7: End If8: using sw As StreamWriter = New StreamWriter(Server.MapPath(fileName))9: sw.WriteLine("Processing " + a.ToString() + " of " + totCount.ToString() + " emails")10: End Using11: Catch 12:Ā  13: End Try14: System.Threading.Thread.Sleep(2000)15: Next16: End Sub
Notice that, system will be in the loop for 500 times and each time before start processing it will update the status which will display to the browser. The Try/Catch block is updating the status where as notice the line no 14 in which I pause the thread. You can add your email sending or other long process stuff here but for me it is enough to sleep the thread for twenty seconds.Let me show you what happen when the task gets finished.
1: Public Sub TaskCompleted(ByVal R As IAsyncResult)2: Try3: using sw As StreamWriter = New StreamWriter(Server.MapPath(fileName))4: sw.WriteLine("Process has been completed successfully <a href='default.aspx'>Click here </a> to go back") 'You might shoot an email or some thing else here5: End Using6: If File.Exists(fileName)7: File.Delete(fileName)8: End If9: Catch 10:Ā  11: End Try12: End Sub
This time, we have updated the status with some other text and a hyper link. You can also have any kind of alert here. This is just the part of the code behind stuff. ASPX file contain the actual Asynchronous logic here is the HTML
1: <form id="form1" runat="server">2: <div>3:Ā  4: <asp:Button ID="Button1" runat="server" Text="Start IAsync" />5: <div id="resultDiv"></div>6: </div>7: </form>
The resultDiv is responsible of showing the status. Now to get the status following Javscript will do the complete magic
1: <script language="javascript">2: var request = false;3: try {4: request = new XMLHttpRequest();5: } catch (trymicrosoft) {6: try {7: request = new ActiveXObject("Msxml2.XMLHTTP");8: } catch (othermicrosoft) {9: try {10: request = new ActiveXObject("Microsoft.XMLHTTP");11: } catch (failed) {12: request = false;13: } 14: }15: }16: 17: function GetResult(filename) {18: var rnd = Math.random() * 1000000;19: var url = filename + '?rnd=' + rnd;20: request.open("GET", url, true);21: request.onreadystatechange = GetResultComplete;22: request.send(null);23: }24: function GetResultComplete() {25: if (request.readyState == 4) {26: 27: if (request.status == 200) {28: var divComm = document.getElementById('resultDiv');29: if (divComm) {30: divComm.innerHTML = request.responseText;31: }32: }33: }34: }35: </script>
There it is ... we are all done. Following is the snapshot of the working long waited task in asp.netasyncYou can find the complete code for Visual Studio 2008 ... cheers

Validate username using custom validation (AJAX)

In this post, I will explain you how to have an ajax call on custom validator control and check for the username in the database. This task will include two pages one is the form page (default.aspx in our case) in which we have the custom validator and the other one is the page which we call through AJAX to give us the result (validateUser.aspx). You can also have a web service instead of that page but in my scenario , I am using ASPX page.

So, the form will look like as following.

 

   1: <form id="form1" runat="server">
   2: <div>
   3: <asp:Panel ID="pnl1" runat="server" DefaultButton="Button1">
   4:     <asp:TextBox ID="TextBox1" runat="server">
   5:     </asp:TextBox>
   6:     <asp:Button ID="Button1" runat="server" Text="Submit" />
   7:     <asp:HiddenField ID="hfOutput" runat="server" />
   8: </asp:Panel>
   9:     <asp:customvalidator ID="Customvalidator1" runat="server" errormessage="Enter Valid User" ControlToValidate="TextBox1" ClientValidationFunction="ValidMe"></asp:customvalidator>    
  10: </div>
  11: </form>

Default.aspx (Form)

Notice, the hiddent field called hfOutput which we will use to store the output of the AJAX call.

Where as the page which we call through AJAX will look like as follows

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="validateUser.aspx.cs" Inherits="LearnWebApp.validateUser" %>

validateUser.aspx

In short, we have deleted every thing from this page except page directive. Now if we call this page we will see the simple output without having any HTML tag. we did it because we want to get rid from all the html tags so that we can have a neat and clean output at the time we call this page from Javascript (AJAX). What we want this page to return us is either "True" or "False". If you look at the code behind file of this page you will have a good idea of what we actually upto. Here is the code for that.

   1: protected void Page_Load(object sender, EventArgs e)
   2:         {
   3:             // We can also use a database call here ... right now we are compairing string.
   4:             if (Request.QueryString["username"] == "username")
   5:             {
   6:                 Response.Write("true");
   7:             }
   8:             else 
   9:             {
  10:                 Response.Write("false");
  11:             }
  12:         }

validateUser.aspx.cs

As it is there on comments, here we are only comparing string. You can have a database call and return the result accordingly.

To call the validateUser.aspx from validMe function which we have defined in ClientValidationFunction property of custom validator, we need to write the following javascript on default.aspx

   1: <script type="text/javascript">
   2:         var ajaxCalled = false;
   3:         
   4:         function ValidMe(source, args) {
   5:            callPage(args.Value)
   6:            while (document.getElementById("hfOutput").value != ""){
   7:                 if (document.getElementById("hfOutput").value == "true") {
   8:                     args.IsValid = true;
   9:                 }
  10:                 else {
  11:                     args.IsValid = false;
  12:                 }
  13:                 document.getElementById("hfOutput").value = "";
  14:                 return;
  15:             }
  16:         }
  17:  
  18:         function callPage(strName) {
  19:             var rnd = Math.random() * 1000000;
  20:  
  21:             if (window.XMLHttpRequest) { // Mozilla, Safari, IE7...
  22:                 request = new XMLHttpRequest();
  23:             } else if (window.ActiveXObject) { // IE6 and older
  24:                 request = new ActiveXObject("Microsoft.XMLHTTP");
  25:             }
  26:             var url = 'validateUser.aspx?username=' + strName + '&R=' + rnd;
  27:             request.open("GET", url, true);
  28:             request.onreadystatechange = SetPage;
  29:             request.send(null);
  30:             
  31:         }
  32:  
  33:  
  34:         function SetPage() {
  35:             if (request.readyState == 4) {
  36:                 var objHf = document.getElementById("hfOutput");
  37:                 if (request.status == 200) {
  38:                     if (objHf) {
  39:                         objHf.value = request.responseText;
  40:                     }
  41:                 }
  42:             }
  43:             
  44:         }
  45:     </script>

 

Let me describe what we have done here, I am calling CallPage function from ValidMe which will call from the asp.net validation mechanism. CallPage function is an AJAX call which will call validateUser.aspx and SetPage function will be called once the AJAX call is finish and we have output ready to use.

And on that SetPage function we are setting the Hidden field  called hfOutput to get used by ValidMe function.

That's it ..... :) . You can also download the complete project give below.