Creating server controls at runtime using HTTP modules


Introduction

In this article, I would like to share a very simple application that I made just now using HTTP modules.

It's all about generating dynamic asp.net server controls using HTTP modules. I only wanted to play around with the stuff and henceforth came out with such an application and thought to share this with others. So nothing much to describe about my application. It is a simple form with two textbox control respectively Name, Age and a country dropdown with a button.

The intention was to create the controls at runtime, populate the list controls, perform some client side validations and after the page validation to access the control values.

Background

Creating controls at runtime in asp.net is pretty cool and can be done easily in many ways. Some really good articles are available on the net. But I wanted to do it in a different manner and so thought of why not give a shot with Http Modules! After all, let's have it's taste.

However, in this article I won't go into the details of the Http Handlers as many good articles are readily available and one can get a good learning overview from them. I would like to concentrate more on the topic that I made after a short introduction.

A brief about HTTP Modules

Asp.net handles each request in a pipeline. HTTPModule and HTTPHandler are the two processing point of this pipeline.

Each time a request is made, that is passed through a number of HTTP modules and lastly is assigned to HTTP handler that decides how the system will behave/respond as per the request. After the request handler has processed the request, the response goes back to the application again through the HTTP modules.

So, HTTP modules are executed before and after the handler are executed and provide a method for interacting with the request

Prerequisites

The .NET 3.5 Framework

Creation of the Custom HTTP Module

The creation of the HTTP module is as simple as creating an ordinary .net class with the difference that the class must implement IHttpModule interface of System.Web namespace.

The interface has two methods which are listed down

  1. void Init(HttpApplication);
  2. void Dispose();

Step 1: Create a new asp.net website and choose the language as C#

Step 2: Right click on the project and choose a class from the Add New Item dialog box.

Step 3: Make sure that the class created is inheriting the IHttpModule interface and implement the methods listed above.

Registering HTTP Modules

Once the above steps are done, we need to register the custom handler in the web.config file. So, open the web.config file and search for the <httpModules ></httpModules> section. Next use the following syntax:

<httpModules>
   <add name="[ModuleName]"  type="[Assembly]" />
</httpModules>
 
Dynamic control generation and Access by HTTP modules

In this application, I created 2 textboxes, namely Name and Age and a country dropdown.

A Submit button is there whose function is to perform client side validation only on the Age field if it is greater than 50 and if the page is a valid one, it will access the values.

Step 1: The DynamicControls.cs class inherites from System.Web.UI.Page, IHttpModule and implements the methods of IHttpModule which are described earlier.

Step 2: In the Init method I called the PreRequestHandlerExecute event of HttpApplication class

//Implementation of init method

    public new void Init(HttpApplication context)

    {

        context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);

    }

The handler method of the same is responsible for checking the valid page and if found creates the controls in the Init() method and fills the country dropdown in the Load() event.

//PreRequestHandlerExecute called

    //Purpose: If a valid page is found, then call the various events of the page

    //          for performing the operations

    void context_PreRequestHandlerExecute(object sender, EventArgs e)

    {

        //Gets the current http context

        System.Web.HttpContext _httpContext = System.Web.HttpContext.Current;

 

 

        if (_httpContext != null)

        {

            _page = _httpContext.Handler as System.Web.UI.Page;

 

            //Valid page found

            if (_page != null)

            {

               //Create controls

                _page.Init += new EventHandler(_page_Init);

 

                //Fill list controls(e.g. dropdowns)

                _page.Load += new EventHandler(_page_Load);

            }

            else

            {

                return;

            }

        }

        else

        {

            return;

        }

 

    }

Step 3: The ControlCreation.cs class basically creates the dynamic controls. The controls are placed in a table for proper positioning.

//Function : CreateControls

    //Purpose: To create the controls

    public void CreateControls(System.Web.UI.Page _pg)

    {

       

        //Building the controls

        BuildGrid(_table, _lblName, _lblAge, _lblCountry, _txtAge, _txtName, _rdBLstSex, _ddCountryList, _btnSubmit);

        _pg.Form.Controls.Add(_table);

    }

Step 4: The FillCountry.cs class is responsible for populating the country dropdown.

//Function Name:PopulateCountry

    //Purpose: Fill country dropdown

    public void PopulateCountry(System.Web.UI.Page _pg)

    {

        DataTable _dtCountry = GetCountryList();

 

        DropDownList _ddlCountryList = _pg.FindControl("ddlCountryList") as DropDownList;

        _ddlCountryList.AutoPostBack = true;

 

        if (_dtCountry != null)

        {

            if (_dtCountry.Rows.Count > 0)

            {

                AddBlankRow(ref _dtCountry, 0);

                Populate(_dtCountry, _ddlCountryList);

            }

        }

    }

Step 5: The Age textbox only allows the numeric value. The javascript function AllowNumeric() is written in the Validation.js file.  Also , user cannot enter an age more than 50years which is called from the submit button.

private void ButtonAttributes(out Button _btnSubmit)

    {

        _btnSubmit = new Button();

        _btnSubmit.ID = "btnSubmit";

        _btnSubmit.Text = "Submit";

        _btnSubmit.Style.Add("background", "#ffeec6");

        _btnSubmit.Attributes.Add("onmouseover", "this.style.background='orange'");

        _btnSubmit.Attributes.Add("onmouseout", "this.style.background='#ffeec6'");

        _btnSubmit.Attributes.Add("onClick", "return CheckAge('txtAge');");

 

        //If a valid page is found then access the data

        _btnSubmit.Click += new EventHandler(_btnSubmit_Click);

 

    }

Step 6: For accessing the data once the page is validated, the Submit button's click event is fired

private string AccessControlValues(string _value)

    {

        if (_page.FindControl("txtName") != null)

        {

            TextBox _txtName = (TextBox)_page.FindControl("txtName");

            _value = _txtName.Text;

        }

 

        if (_page.FindControl("txtAge") != null)

        {

            TextBox _txtAge = (TextBox)_page.FindControl("txtAge");

            _value = _txtAge.Text;

        }

 

        if (_page.FindControl("ddlCountryList") != null)

        {

            DropDownList _ddlCountryList = (DropDownList)_page.FindControl("ddlCountryList");

            _value = _ddlCountryList.SelectedItem.Text;

        }

 

        return _value;

    }  

Registering the Httpmodule

The way of doing it is explained earlier. However, I have pasted the configuration section for this sample application

<httpModules>

     <add name="DynamicControls" type="DynamicControls"/>

</httpModules>

Advantages Of Http Modules

Http Modules are a handy tool for the asp.net developers. Some of the advantages are listed here:

  1. HTTP modules can be added at the site, folder, or file level as opposed to ISAPI filters, which could only be added at the global or site level
  2. Can be reuse across application.

Conclusion

This is just an example of showing a small task that can be accomplished by Http Modules mainly indented for the beginners. It is only a drop of water in the big ocean. The real strength of the Http Modules are immense like

  1. Custom caching and session handling mechanism
  2. Converting http to https and vice versa
  3. User authentication etc.


Similar Articles