Click here to Skip to main content
Click here to Skip to main content

Creating Server Controls at Runtime using HTTP Modules

, 5 Apr 2009
Rate this:
Please Sign up or sign in to vote.
This is a demonstration to show how to create a dynamic server control using HTTP modules
Click to enlarge image

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 of sharing this with others. So nothing much to describe about my application. It is a simple form with two textbox controls 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, why not give a shot with HTTP Modules! After all, let’s have its 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 points of this pipeline. Each time a request is made, that is passed through a number of HTTP modules and lastly is assigned to a 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. For more information, please refer to the following links:

Prerequisites

  • The .NET 3.0 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 below:

  • void Init(HttpApplication);
  • 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 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 two 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 inherits 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 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 5: 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 6: The Age textbox only allows the numeric value. The JavaScript function AllowNumeric() is written in the Validation.js file. Also, the user cannot enter an age more than 50 years 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 7: 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 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 reused across the application.

Conclusion

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

  1. Custom caching and session handling mechanism
  2. Converting HTTP to HTTPS and vice versa
  3. User authentication, etc.

History

  • 5th April, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Niladri_Biswas
Tester / Quality Assurance
India India
Software Engineer at Edco

Comments and Discussions

 
Questionhow to retrieve all fields back added at runtime... Pinmembershailendra_csp16-Sep-09 23:15 
GeneralNice example Pinmembersatishsuthar6-Apr-09 20:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 5 Apr 2009
Article Copyright 2009 by Niladri_Biswas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid