Statistics
Visits: 105080
Page Visits: 139135
Active visitors (monthly): 5364
Feed Count: 45
Most visited page: Adding value as a technical analyst
Category : ASP.NET AJAX

A minor design flaw in Microsoft AJAX library

Microsoft AJAX Library is a good javascript library for building AJAX components, behaviours, and controls. It is widely used by AJAXControlToolkit. Microsoft AJAX Library has a central class called PageRequestManager. A singleton object of this class is initialized when you put an UpdatePanel in the aspx page.

PageRequestManager provides events which you can handle. A common use is to cancel the AJAX request if another AJAX request is running. This is the common structure of javascript code that uses the PageRequestManager.


var prm = Sys.Webforms.PageRequestManager.get_instance();
prm.add_beginRequest(function() {});

There are two events that are raised before a AJAX request is invoked: initializeRequest, beginRequest. The request body can be got using code like this:


var prm = Sys.Webforms.PageRequestManager.get_instance();
orm.add_initializeRequest(
   function(sender, args) {
      alert(args.get_request().get_body());
   });

I have a requirement where I want to modify the values of a textbox when some conditions are met. This should be done after the user clicks the button but before the AJAX request is invoked. I have multiple buttons / GridView links in the page which are AJAX enabled.

I hooked into the PageRequestManager initializeRequest(). I modified the textbox values. However, the server did not get the modified values. It appears that the request body is prepared before the initializeRequest() event is raised.

The worst part is that the library does not allow me to modify the request body using a simple API. Sys.Net.WebRequest has a method to set the request body using the set_body() function. But, there is no programatic API to set the value of the textbox using an ID or name.

One more reason why the Microsoft AJAX library did not become popular!

Permalink | No Comments | Leave your comment
 

Auto-save draft documents

While composing large documents, an auto-save feature can be provided. The document can be saved from a RichEdit control on to the backend cache using the AJAX timer control.

<edit:ComposeEditor ID="PostEditor" runat="server" Width="700" Height="500" AutoFocus="true">
<asp:UpdatePanel ID="TimerPanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
    <asp:Label ID="TimerLbl" runat="server" ForeColor="Blue"></asp:Label>
    <asp:Timer ID="EditorTimer" runat="server" Interval="10000" OnTick="EditorTimer_Tick">
    </asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel>

This method can be used with big forms as well. As the UpdatePanel automatically posts the entire viewstate, the state of other controls is available in the postback. The timer event handler that does the saving is shown below:

protected void EditorTimer_Tick(object sender, EventArgs e)
{
    post.Contents = PostEditor.Content;
     // Save the contents of the editor
    TimerLbl.Text = String.Format("Draft autosaved at {0}", ISTime.Now.ToLongTimeString());
}
Permalink | No Comments | Leave your comment
 

Customizing AJAX HTMLEditor Control

The toolbar buttons in the HTMLEditor control of AJAX Control Toolkit can be customized. For this, create a new server control deriving from HTML Editor and override the FillTopToolbar() method as follows:

public class LiteEditor : Editor
{
    protected override void FillTopToolbar()
    {
        TopToolbar.Buttons.Add(new Bold());
        TopToolbar.Buttons.Add(new Italic());
        TopToolbar.Buttons.Add(new Underline());
        TopToolbar.Buttons.Add(new Paragraph());
        TopToolbar.Buttons.Add(new OrderedList());
        TopToolbar.Buttons.Add(new AjaxControlToolkit.HTMLEditor.ToolbarButton.BulletedList());
        TopToolbar.Buttons.Add(new ForeColor());
        TopToolbar.Buttons.Add(new ForeColorSelector());
        TopToolbar.Buttons.Add(new ForeColorClear());
    }

Bold, Italic are pre-defined buttons available within AJAXControlToolkit.HTMLEditor namespace.

Permalink | 2 Comments | Leave your comment
 
Commented by Vijay at 27-Apr-2011 12:16 PM

What I understand is that you want to add your own toolbar button as well as the dialog. For this, you will have to download the source code from Codeplex and do some more tinkering.

Commented by RaVi at 20-Nov-2010 11:09 AM

How can i add my own popup button to the toolbar

Prevent multiple AJAX postbacks

To prevent multiple AJAX postbacks at the same time, the following code can be used:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_BeginRequest(abortPostbacks);

function abortPostbacks(sender, args) {
    if (prm.isInAsyncPostBack)
        args.set_cancel(true);
}
Sys.WebForms.PageRequestManager is the core class of Microsoft AJAX library. It takes care of AJAX life cycle at the browser. It has lot of useful methods and events. In the above code, we can trap the BeginRequest event that is fired for each AJAX request. If there is an already an AJAX request (isInAsyncCallBack), the current request can be cancelled.
Permalink | 3 Comments | Leave your comment
 
Commented by Måns at 14-Feb-2011 05:50 PM

Correct syntax is:


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

function abortPostbacks(sender, args) {
   if (prm.get_isInAsyncPostBack())
       args.set_cancel(true);
}

Commented by Vijay at 05-Feb-2011 07:00 PM

The function should be called for all ajax calls within the page which should not be invoked when another ajax call is running in the page.

Commented by muzammil ahmed at 28-Jan-2011 11:23 AM

Where do you need to add this piece of code? thanks.

Problems with AJAX TabContainer

AJAX TabContainer has quite a few problems. This article gives a good idea of how to work around some of these problems. The most annoying problem is not able to set the styling of the TabContainer tabs. Here is a good link to overcome the problem by tinkering with the source code. The link examines the CSS emitted by the TabContainer and modifies the styles in the target page.

Another annoying feature of the TabContainer is the ActiveTabChanged event. If the TabIndex is changed by clicking on the tab, there is no AJAX styled postback. This prevents refreshing GridViews if grids are embedded within the TabContainer. Here is a good post of how to ensure that the server side ActiveTabChanged event is raised.

Permalink | No Comments | Leave your comment
 

ACT vs JQuery

ACT (AjaxControlToolkit) and JQuery offers gave UI flexibility for asp.net developers. ACT can be used for WebForms while JQuery can be used for ASP.NET MVC. Here are the equivalent controls in ACT and JQuery that are popular:

ACT TabContainer and JQuery Tabs

ACT CalendarExtender and JQuery DatePicker

ACT Accordion and JQuery Accordion

ACT ReorderList and JQuery Sortable

ACT ModalPopupExtender and JQuery Dialogs

The key difference between the two is that ACT is based on Microsoft AJAX client scripts whereas JQuery is purely javascript based and used by popular websites including Google.

Permalink | No Comments | Leave your comment
 

Using XMLHttpRequest

Here is a demo of creating a XMLHttpRequest object and processing the response asynchronously. The server time is captured using a simple handler file and is written onto a label in the page. This refresh happens every second and happens using AJAX

Here is the HTML markup for the page. The body onload calls the function ajaxTime every second. The ajaxTime updates the label with the time at the server.


<body onload="setInterval('ajaxTime();',1000);">
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblServerTime" runat="server"></asp:Label>
    </div>
    </form>
</body>

The javascript for ajaxTime function is as below. For all browsers, create a new XMLHttpRequest object directly. For IE 6, create the object using the ActiveXObject interface. Handle the onreadystatechange event for processing the response and updating the label. The open method points to the page which will give us the server time.

function ajaxTime() {

    var xmlHttp;

    if (window.XMLHttpRequest) {
        // for all modern browsers
        xmlHttp = new XMLHttpRequest();
    }
    else {
        // for IE 6.0
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }


    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
            document.getElementById('lblServerTime').innerText = xmlHttp.responseText;
        }
    }
    
    xmlHttp.open('GET', 'ServerTime.ashx', true);
    xmlHttp.send(null);

}

The code for handler is straight-forward and is shown below:

public void ProcessRequest(HttpContext context)
{
    context.Response.Expires = -1;
    context.Response.ContentType = "text/plain";
    context.Response.Write(DateTime.Now.ToString());
}

Permalink | No Comments | Leave your comment
 

WebMethod Example

I want a label box to be refreshed every one second with a random number generated at the server

This is a classic example of WebMethods. WebMethods are written on the server side in the page class. WebMethods are static. Here is a simple implementation of a webmethod:


private static Random random = new Random(1000);

[WebMethod]
public static int GetRandomNumber()
{
    return random.Next(10, 99);
}

To be able to call this WebMethod from Javascript, the asp:ScriptManager should have the EnablePageMethods property set to true:


<form id="form1" runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:Label ID="Random" runat="server"></asp:Label>
</form>

From Javascript, the WebMethod can be called using the syntax PageMethods.FunctionName(Arg0, Arg1, OnSucceededCallBack); WebMethods are executed asynchronously. So a callback function has to be provided. Here is an example of updating a label box with the random number

<script type="text/javascript">

    setTimeout("PageMethods.GetRandomNumber(setRandom);", 1000);

    function setRandom(result) {
        document.getElementById("Random").innerText = result;
        setTimeout("PageMethods.GetRandomNumber(setRandom);", 1000);
    }
        
</script>

Permalink | 1 Comment | Leave your comment
 
Commented by rajni at 07-Nov-2011 12:25 PM

its not working please give any other example of ajax web method.