Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

ASP.NET AJAX Web Form Generation at Run time

ASP.NET AJAX consists of client-script libraries and server components that are integrated to provide a robust development framework, which allow us to build rich client applications quickly and easily.

 

Whenever a postback happens in a normal ASP.NET page the whole ASP.NET page will be refreshed. But AJAX Enabled ASP.NET web page will enable partial rendering of a web page as the result of an asynchronous postback.

Creating a Basic AJAX Web Form declaratively is very easy and looks like code bellow:

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
 
<body>
<form id="form2" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Path="clientscript.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button" />
</form>
</body>
</html>

But, in Some situations we need to create some of the Web Controls  which make the AJAX Web Form dynamically at runtime. in these scenario's we need to follow some basic steps.

Dynamically generating a htmlForm and adding Controls

HtmlForm class is used to generate a Web Form dynamically as below. Any control which needs to be generated dynamically at runtime is needs to be created in the PreInit event of the Page class. Don't initiate any values for controls here, because if the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

protected void Page_PreInit(object sender, EventArgs e)
{
    HtmlForm form = new HtmlForm();
    Label label = new Label();
    form.Controls.Add(label);
    this.Controls.Add(form);
}

How to dynamically generate a ScriptManager Control

A ScriptManager control is needed on every page that would support partial-page rendering. Instead of adding it to every page we can create it in a Base class and derive all of the web pages from it which needs to support asynchronous postback's.

The ScriptManager control keeps track of all the update panels on the page and of their triggers. It coordinates partial-page rendering behavior on the server, and determines which sections of the page to render as a result of an asynchronous postback. It makes script resources available to the browser including ASP.NET AJAX library.

We need to ensure whether the page is currently having any ScriptManager before generating a new one. You should not add a control directly to a Web Form because the code generated for the control will be inserted at the end of the HTML stream or just after the </html> closing tag. Either we need to add the control to a PlaceHolder control which is already defined or add it to the HtmlForm control of the page. ScriptManager control needs to be the first control of the HtmlForm. We need to set the EnablePatialRendering to true then only it will enable partial rendering.

protected void Page_PreInit(object sender, EventArgs e)
{
    if (ScriptManager.GetCurrent(this.Page) == null)
    {
        ScriptManager SManager = new ScriptManager();
        SManager.EnablePartialRendering = true;
        foreach (Control c in this.Controls)
        {
            if (c is HtmlForm)
            {
                c.Controls.AddAt(0, SManager);
            }
        }
    }
}

Creating UpdatePanel Control Programmatically

An UpdatePanel control is used to refresh selected parts of the page instead of refreshing the whole page, with an asynchronous postback. A Web page that contains a ScriptManager control and one or more UpdatePanel controls can automatically participate in partial-page updates, without custom client script.

To add an UpdatePanel control to a page at runtime, create a new instance of the UpdatePanel control. Then add controls to it by using the ContentTemplateContainer property and the AddControl() method. When an UpdatePanel control is added programmatically, only postbacks from controls in the same naming container as the UpdatePanel control can be used as triggers for the panel.

If the updatepanel's are not nested we can update each panel independently by setting the UpdateMode property to Conditional. The default value of the UpdateMode property is Always. This causes the panel to refresh in response to any asynchronous postback occured on the whole page.

UpdatePanel UPanel = new UpdatePanel();
UPanel.ContentTemplateContainer.Controls.Add(label);
UPanel.ContentTemplateContainer.Controls.Add(button);
UPanel.UpdateMode = UpdatePanelUpdateMode.Conditional;

How to Create AsyncPostBackTrigger's and Register them with the UpdatePanel

Controls that trigger an UpdatePanel control to refresh are registered with the ScriptManager control on the page. This occurs automatically for the child controls that are part of an UpdatePanel control's ContentTemplate. But if any Control which is out side of the UpdatePanel and wants to trigger the UpdatePanel, we need to use the RegisterAsyncPostBackControl(Control) method of the ScriptManager control to programmatically register a postback control and then call the Update() method of the UpdatePanel when the control posts back. Programmatically adding AsyncPostBackTrigger controls is not supported.

protected void Page_Load(object sender, EventArgs e)
{
    SManager.RegisterAsyncPostBackControl(linkButton);
}

private void lb_Click(object sender, EventArgs e)
{
    label.Text = label.Text + System.Environment.NewLine + "-->Link Button Clicked";
    UPanel.Update();
}

Registering Web Services

Microsoft ASP.NET AJAX enables you to call ASP.NET Web services (.asmx files) from the browser by using client script. This enhances the user experience for the Web application. The ASP.NET AJAX framework generates a client proxy object for each ServiceReference object in the Services collection. The proxy classes and their strongly typed members simplify using Web services from client script. Proxy classes are derived from the Sys.Net.WebServiceProxy class.

Keeping web service url's in web.config file makes it easier to change the web services dynamically without recompile. The ScriptManager control's Services collection contains a ServiceReference object for each Web service that is registered with the ScriptManager control. We can programmatically add ServiceReference objects to the Services collection to register Web services at run time so that we can change the web services dynamically with out recompiling.

WS = new ServiceReference(@"~/WebService.asmx");
SManager.Services.Add(WS);

Registering Custom Script

ScriptManager control is used to manage resources for controls that participate in partial-page updates. Resources include scripts, styles, hidden fields, and arrays. The Scripts collection of the ScriptManager control contains a ScriptReference object for each script that is available to the browser. You can specify the scripts declaratively or programmatically as following.

ScriptReference SR = new ScriptReference();
SR.Path = @"~/ClientScript.js";
SManager.Scripts.Add(SR);

This tutorial is written by RELIANCE CONSULTING.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |