Click here to Skip to main content
11,921,491 members (69,692 online)
Click here to Skip to main content
Add your own
alternative version


33 bookmarked

Manage ASP.NET Server Controls, Event Handlers, and Server-Side Validation Using XML and XSLT

, 18 Apr 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on managing ASP.NET server controls, event handlers, and server-side validation using XML and XSLT.


In most cases, server controls are very useful in ASP.NET web applications since they have some valuable events (for example, click event, data binding event, data bound event, etc.) and many advance functionalities like state management, input validation, etc. In general, XSLT produces plain XML or HTML without any hassle, but if we want to create our ASP.NET server control by using XML and XSLT, then we should follow some procedures which will be described below.

XML has vast uses in web applications, and when we combine XML and XSLT, it shows its own strength and beauty which can speed up our application very much. One major benefit of using XML is column flexibility. Suppose there are two types of addresses in our application: home address and office address. This number can be increased or decreased anytime without changing much code. And using XSLT, we will not just create server controls, but also define their events which will work like a magic.


I am assuming that the reader of this article has basic knowledge of XML, XSLT and ASP.NET.

Using the code

We will follow these steps to get things done:

  • Prepare the XML document
  • Prepare the XSLT document to transform the XML data
  • Write the C# code to instantiate the controls and event handlers

Consider the following XML:

  <Employee Id="1">
      <Address Caption="Address">
        <Home Caption="Home 1">
          <Street Caption="Street 1" Type="Text">Road#  27, House# 13, Banani</Street>
          <Street Caption="Street 2" Type="Text">
          <City Caption="City" Type="Text" Required="yes">Dhaka</City>
          <Zip Caption="Zip" Type="Text">1213</Zip>
          <Country Caption="Country" Type="CountryDDL">BD</Country>
        <Home Caption="Home 2">
          <Street Caption="Street 1" Type="Text">Sector-  10</Street>
          <Street Caption="Street 2" Type="Text">Uttara</Street>
          <Street Caption="Street 3" Type="Text">
          <City Caption="City" Type="Text" Required="yes">Dhaka</City>
          <Zip Caption="Zip" Type="Text">1230</Zip>
          <Country Caption="Country" Type="CountryDDL">BD</Country>
  <Employee Id="2">
      <Address Caption="Address">
        <Home Caption="Home 1">
          <Street Caption="Street 1" Type="Text">J-13,  Road 27</Street>
          <Street Caption="Street 2" Type="Text">Banani</Street>
          <City Caption="City" Type="Text">Dhaka</City>
          <Zip Caption="Zip" Type="Text">1213</Zip>
          <Country Caption="Country" Type="CountryDDL">BD</Country>
        <Home Caption="Home 2">
          <Street Caption="Street 1" Type="Text">Michigan Avenue</Street>
          <Street Caption="Street 2" Type="Text">Suite 2800</Street>
          <Street Caption="Street 3" Type="Text">
          <City Caption="City" Type="Text">Chicago</City>
          <Zip Caption="Zip" Type="Text">60601</Zip>
          <Country Caption="Country" Type="CountryDDL">USA</Country>

We have to show the addresses like below:


Since there are multiple employee’s data in our XML document, we have to select the requested employee’s data among them. For this purpose, we have to create an argument list and need to pass the employee ID through the XSLT parameter.

//create argument list
XsltArgumentList xslArg = new XsltArgumentList();
xslArg.AddParam("employeeId",  "", ddlEmployee.SelectedValue);

//load the data
XPathDocument xdoc = new XPathDocument(Server.MapPath("Address.xml"));
//load Xslt
XslCompiledTransform transform  = new XslCompiledTransform();
StringWriter sw = new  StringWriter();

//transform it
transform.Transform(xdoc, xslArg,  sw);

And, we will receive the argument from XSLT like below:

<!--<xsl:param  name="employeeId"/>-->
<xsl:param name="employeeId"/>

If we see look at the XML, then we will find that there is a ‘Caption’ attribute in each node. This is the caption of each value while showing the output. On the other hand, to give input, sometimes it is better to show a dropdown list rather than a traditional textbox. For instance, when the user has to choose country name, it is more meaningful to show a country list rather than a textbox. To fulfill this purpose, we have a similar attribute named ‘type’ in the XML nodes. And by inspecting this attribute, we can render the appropriate ASP.NET server control from XSLT.

 <xsl:when test="translate($varType,$up,$lo)='countryddl'">
    <asp:DropDownList  id="{concat('ddlCountry',$rowindex)}" runat="server" 
    DataTextField="Text" DataValueField="Value">
          <asp:ListItem  value="{.}">
                <xsl:value-of  select="."/>
    <asp:TextBox ID="{$varId}" runat="server" 
       Text="{.}" width="205px" ></asp:TextBox>
    <xsl:if test="translate($isRequired,$up,$lo)='yes'">
          <asp:RequiredFieldValidator  ErrorMessage=" 
                Required Field" runat="server" 
    ControlToValidate="{$varId}" />

At last, we must declare a button to save the input data in XSLT:

<asp:Button  ID="btnSaveAddress" runat="server" BackColor="White"
   BorderColor="DeepSkyBlue" BorderStyle="Solid" 
   BorderWidth="1px" Font-Names="Tahoma" 
   Font-Size="10pt" Text="Save Data" />

Now, we have to set the event handler for this button from the code behind. The ParseControl function will make our work very easy by parsing the XML string to an ASP.NET server control. To get a reference of newly created controls, we have to call the FindControl method. As soon as we get the reference of the control, we can set the event handler for that control. One thing that is very important to know is that the event handler adding process should be after parsing the control. Because, before parsing, the control will not be available. Also, the parsing should be in the Page_Init event so that the controls will be available in the rest of the page life cycle.

//parse control
Control ctrl = Page.ParseControl(result);

//find control to add event handler
Button btnSaveAddress = (Button)phEmployeeAddress.FindControl("btnSaveAddress");
btnSaveAddress.Click += new EventHandler(btnSaveAddress_Click);

We have almost covered everything. The most interesting thing is, using XSLT, our ASPX page will become very simple and clear. Here is the full ASPX source:

<%@ Page Language="C#" 
    AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
  <head runat="server">
      <title>Dynamic Controls Using Xslt</title>
      <form id="form1" runat="server">
      <div style="float: right; background-color: Yellow">
          <asp:Label ID="lblMessage"  runat="server" 
          <asp:Label ID="Label1" runat="server" 
             Text="Choose  Employee"></asp:Label>
          <asp:DropDownList ID="ddlEmployee" 
                     runat="server" Width="128px">
              <asp:ListItem Value="1">Ehsan</asp:ListItem>
              <asp:ListItem Value="2">Ashraf</asp:ListItem>
           <asp:Button ID="btnLoadData" runat="server" 
               BackColor="White" BorderColor="DeepSkyBlue" 
               BorderStyle="Solid" BorderWidth="1px"  
               Font-Names="Tahoma" Font-Size="10pt" 
               Text="Load  Data" 
               OnClick="btnLoadData_Click"  /><br />
          <br />
          <asp:PlaceHolder ID="phEmployeeAddress" 

All the XSLT controls will be extracted to the PlaceHolder, and here is the entire XSLT used to render the HTML and server controls:

<xsl:stylesheet  version="1.0" 
    <xsl:output method="xml" indent="yes" 
       encoding="utf-8" omit-xml-declaration="yes"/>
    <!--<xsl:param name="employeeId"/>-->
    <xsl:param name="employeeId"/>
    <xsl:template match="/root">
      <xsl:for-each select="Employee">
        <xsl:if test="@Id = $employeeId">
        <table width="100%" border="0" 
               cellspacing="0" cellpadding="0" 
                 <xsl:apply-templates  select="Address">
                  <!--<xsl:with-param name="count" 


ASP.NET server controls are very powerful in web applications without any doubt, and by combining XML and XSLT with it, we can make web applications more powerful, easier, efficient, and re-usable. Also, by using XML and XSLT, the application UI script will look clean and will be easier to maintain. I hope this will be a great start for those who want to make their site more dynamic and structured using XML and XSLT with the great power of ASP.NET controls. Enjoy!


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


About the Author

Ehsanul Haque
Software Developer (Senior) Desme Inc
Bangladesh Bangladesh
Ehsanul Haque is a Software Engineer, who is dedicated to Microsoft .NET based development. He is involved with several US based software projects from his country. Already he has completed few projects, which are being used by several users of different countries, such as USA, Japan, and Bangladesh. While developing and managing a team, he maintains a set of well defined engineering practices developed by him and other online developer community. Beside software development, he has also written several technical articles.

When not engaged with technical stuffs, he likes to pass time with his friends, and family members, listens music, watching TV, travel or by reading books.

You may also be interested in...

Comments and Discussions

GeneralSmall help Pin
Senal17-Feb-10 19:54
memberSenal17-Feb-10 19:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web04 | 2.8.151120.1 | Last Updated 18 Apr 2008
Article Copyright 2008 by Ehsanul Haque
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid