Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Sometimes you need to create dynamic pages. You may allow users to build their own applications by selecting the fields they need. In this article, I will show how to build dynamic applications by using ASP.NET and XML. In this example, I use XML for meta-programming or generative programming. I use XML with an XSLT to generate ASP.NET PRE, utilizing intrinsic ASP.NET parsing methods with the XSLT output. Steps that we need to do:

First, what we need to come up with is a good structure of our page in a XML file. A basic page structure is defined below. The example structure consists of field elements, with attributes, properties and listitems.

<FORM>
  <PAGES>
    <PAGE title="Page Title" id="page_1">
      <FIELDS>
        
    <!-- create regular TextBox -->
    <FIELD type="TextBox" label="Last Name:" required="true">
          <PROPERTIES>
            <PROPERTY name="ID">LAST_NAME</PROPERTY>
          </PROPERTIES>
        </FIELD>

    <!-- create multiline TextBox (textarea) -->
        <FIELD type="TextBox" label="Description:">
          <PROPERTIES>
            <PROPERTY name="ID">DESCRIPTION</PROPERTY>
            <PROPERTY name="TextMode">MultiLine</PROPERTY>
            <PROPERTY name="Cols">30</PROPERTY>
            <PROPERTY name="Rows">2</PROPERTY>
          </PROPERTIES>
        </FIELD>

    <!-- regular textbox prefilled with text -->
    <FIELD type="TextBox" label="Prefilled Contrl:">
          <PROPERTIES>
            <PROPERTY name="ID">PREFILLED_CONTROL</PROPERTY>
            <PROPERTY name="Text">Some Text</PROPERTY>
          </PROPERTIES>
        </FIELD>

        <!-- regular text box which must filled 
                                 and allowed Date datata type -->
        <FIELD type="TextBox" label="Start Date:" 
                      required="true" validation="Date">
          <PROPERTIES>
            <PROPERTY name="ID">START_DATE</PROPERTY>
          </PROPERTIES>
        </FIELD>

    <!-- create select box -->
        <FIELD type="DropDownList" label="Title:">
          <PROPERTIES>
            <PROPERTY name="ID">TITLE</PROPERTY>
          </PROPERTIES>
          <LISTITEMS>
            <LISTITEM value="">Select One</LISTITEM>
            <LISTITEM value="1">Architector</LISTITEM>
            <LISTITEM value="2">Sr. Developer</LISTITEM>
            <LISTITEM value="3">Programmer</LISTITEM>
            <LISTITEM value="4">Web Designer</LISTITEM>
          </LISTITEMS>
        </FIELD>

    <!-- radio buttons list -->    
        <FIELD type="RadioButtonList" label="Are you US citizen?">
          <PROPERTIES>
            <PROPERTY name="ID">IS_US_CITIZEN</PROPERTY>
            <PROPERTY name="RepeatColumns">1</PROPERTY>
            <PROPERTY name="RepeatDirection">Vertical</PROPERTY>
            <PROPERTY name="RepeatLayout">Table</PROPERTY>
            <PROPERTY name="TextAlign">Right</PROPERTY>
          </PROPERTIES>
          <LISTITEMS>
            <LISTITEM value="1">Yes</LISTITEM>
            <LISTITEM value="0">No</LISTITEM>
          </LISTITEMS>
        </FIELD>

    <!-- check box list -->
        <FIELD type="CheckBoxList" label="Languages:">
          <PROPERTIES>
            <PROPERTY name="ID">LANGUAGES</PROPERTY>
            <PROPERTY name="RepeatColumns">1</PROPERTY>
            <PROPERTY name="RepeatDirection">Vertical</PROPERTY>
            <PROPERTY name="RepeatLayout">Table</PROPERTY>
            <PROPERTY name="TextAlign">Right</PROPERTY>
          </PROPERTIES>
          <LISTITEMS>
            <LISTITEM value="C#">C#</LISTITEM>
            <LISTITEM value="Java">Java</LISTITEM>
            <LISTITEM value="VB">Visual Basic</LISTITEM>
          </LISTITEMS>
        </FIELD>

    <!-- here is a hyperlink (a) -->
        <FIELD type="HyperLink">
          <PROPERTIES>
            <PROPERTY name="ID">LINK</PROPERTY>
            <PROPERTY name="NavigateUrl">javascript:void(alert('Hello ooo'));
            </PROPERTY>
            <PROPERTY name="Text">Say Hello</PROPERTY>
          </PROPERTIES>
        </FIELD>

    <FIELD type="html" src="file path"/>

    <!-- you can place here any other asp controls -->

      </FIELDS>
    </PAGE>
    
    ...

  </PAGES>
</FORM>

Next step is to create XSLT style to transform our XML schema The XSLT iterates through each field, first outputting a label for the field as plain text. The stylesheet also checks if the field is required, and adds a RequiredFieldValidator if needed. The stylesheet then creates a Web Control (it could be any valid web control such as TextBox, RadioButtonList, DropDownList, etc.). ListItems are created for each of the ListControls.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" 
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:asp="remove">
  <xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="yes">
  </xsl:output>
  <xsl:template match="/">

   <!-- page id parameter if we have more than 1 page in our XML file -->
   <xsl:param name="pageid"/>

     <!-- start form page -->
     <table cellpadding="0" cellspacing="5">

       <!-- set title of the current page -->
       <tr>
        <td colspan="3" align="center" style="font-size:25px">
         <xsl:value-of select="FORM/PAGES/PAGE[@id=$pageid]/@title" />
        </td>
       </tr>
       <tr><td colspan="3" style="height:20px"></td></tr>

       <!-- iterate through page fields -->
       <xsl:for-each select="FORM/PAGES/PAGE[@id=$pageid]/FIELDS/FIELD">

       <!-- create row -->
       <xsl:element name="tr">
        <xsl:attribute name="id">
          TR_<xsl:value-of select="PROPERTIES/PROPERTY[@name='ID']"></xsl:value-of>
        </xsl:attribute>

        <!-- hide the row -->
        <xsl:if test="@display='none'">
         <xsl:attribute name="style">display:none;</xsl:attribute>
        </xsl:if>

        <xsl:choose>

         <!-- this is the way to place "include" files into your PRE -->
         <xsl:when test="@type='HTML'">
          <td colspan="3">
            <!-- #include file="<xsl:value-of select="@src"></xsl:value-of>" -->
          </td>
         </xsl:when>

         <!-- other controls -->
         <xsl:otherwise>

         <!-- field label column -->
         <td valign="top">
          <xsl:value-of select="@label" />
         </td>

         <!-- field column -->
         <td>

          <!-- field element -->
          <xsl:element name="asp:{@type}">
           <xsl:attribute name="runat">server</xsl:attribute>
           <xsl:for-each select="./PROPERTIES/PROPERTY">
             <xsl:attribute name="{@name}">
               <xsl:value-of select="current()"></xsl:value-of>
             </xsl:attribute>
           </xsl:for-each>
           <xsl:for-each select="./LISTITEMS/LISTITEM">
            <asp:ListItem value="{@value}">
              <xsl:value-of select="current()"></xsl:value-of>
            </asp:ListItem>
           </xsl:for-each>
          </xsl:element>
         </td>

         <!-- validation message column -->
         <td>
          <xsl:if test="@required='true'">
           <asp:RequiredFieldValidator ErrorMessage="Required" runat="server" 
                 ControlToValidate="{PROPERTIES/PROPERTY[@name='ID']}" />
          </xsl:if>

          <xsl:if test="@validation='Date'">
           <asp:CompareValidator ErrorMessage="Dates Only" runat="server" 
                Operator="DataTypeCheck" Type="Date" 
                ControlToValidate="{PROPERTIES/PROPERTY[@name='ID']}" />
          </xsl:if>

          <xsl:if test="@validation='Number'"> 
           <asp:CompareValidator ErrorMessage="Numbers Only" runat="server" 
               Operator="DataTypeCheck" Type="Integer" 
               ControlToValidate="{PROPERTIES/PROPERTY[@name='ID']}" />
          </xsl:if>

          <xsl:if test="@validation='Currency'">
           <asp:CompareValidator ErrorMessage="Currency Only" runat="server" 
               Operator="DataTypeCheck" Type="Currency" 
               ControlToValidate="{PROPERTIES/PROPERTY[@name='ID']}" />
          </xsl:if>
         </td>
        </xsl:otherwise>

       </xsl:choose>
      </xsl:element>

      </xsl:for-each>
     </table>
  </xsl:template>
</xsl:stylesheet>

Our XSLT file has a prefix (xmlns:asp="remove") defined for the XSL namespace. This is used to generate plain HTML. Now we are ready to write our Page transformer.

    ...
    private readonly string XslFile = @"...\default.xslt";
    private readonly string XmlFile = @"...\default.config";

    ...
    private void Page_Load(object sender, System.EventArgs e)
    {
        string pageId = "page_1";

        if (!Page.IsPostBack)
        {

            /**
             * Transform aspx page with fields from xml file
             * Get transform result as a string
             * Parse controls into a parent control holder
             */

            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(XmlFile);

            // load xslt to do transformation

            XslTransform xsl = new XslTransform();
            xsl.Load(XslFile);

            // load xslt arguments to load specific page from xml file

            // this can be used if you have multiple pages

            // in your xml file and you loading them one at a time

            XsltArgumentList xslarg = new XsltArgumentList();
            xslarg.AddParam("pageid", "", pageId);

            // get transformed results

            StringWriter sw = new StringWriter();
            xsl.Transform(xdoc, xslarg, sw);
            string result = sw.ToString().Replace("xmlns:asp=\"remove\"", 
                     "").Replace("&lt;","<").Replace("&gt;",">");
            // free up the memory of objects that are not used anymore

            sw.Close();

            // parse the controls and add it to the page

            Control ctrl = Page.ParseControl(result);
            Page.Controls.Add(ctrl);
        }
    }

    private void BtnSave_Click(object sender, System.EventArgs e)
    {
        // save data into a data container

        // ...

        Response.Write (Request.Form["LAST_NAME"]);
    }

Conclusion

In this article, we separate data from content to make a cleaner design and for better maintainability. When XML is combined with XSLT, ASP.NET server controls become even more powerful. This opens up numerous possibilities for dynamic and robust systems.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
QuestionCode DLL issue
Member 4375269
23:03 11 Mar '10  
Hi could some one provide me

dll for this article

Laugh
Generalneed WTMI.Collections and WTMI.Util
AJRAPA
3:24 11 Mar '10  
Hi,

has anybody a working version?
Please send me: sinhajay@hotmail.com

Thank you.
XAX

GeneralA working version (with WTMI) Please
sim2053
4:33 30 Nov '09  
Hi,

has anybody a working version?
Please send me: sim10berg@gmail.com

Thank you.
GeneralWTMI Please
George.Saraiva
4:42 21 Jul '09  
Someone have code or DLL WTMI.UTIL?
Please send me: antoniog@techbiz.com.br

If you have a version of. NET 2 I want too.
Thank you.
GeneralNeeed working version for asp.net 2.0
ch.ramesh
5:45 19 May '09  
Hi friends,

Pls. send me the code targeting asp.net 2.0.
Thanks in advance
it's urgent
email: cheripelli.ramesh@gmail.com
GeneralWTMI
APTL
8:43 18 Feb '09  
Can you provide me with the WTMI classes. You can email them to arplus@hotmail.com

Thanks.
GeneralWTMI.Util
Member 3970593
1:17 16 Jan '09  
what comes under WTMI.Util. It may be required for ReflectionManager. Please send code for WTMI.Util at rajeev.zp@gmail.com
GeneralReflectionManager
Member 3970593
0:51 16 Jan '09  
i am getting error of ReflectionManager. How to solve it? Please email me code or required dll as rajeev.zp@gmail.com.
GeneralEvent handle in XSLT file
phuongduy2010
5:34 11 Nov '08  
I define xslt file with some button but when i define button which type is always submit . i dont know why. i want to change the type of button but i dont know how i do it.
GeneralOk Why Some Control is visible?
phuongduy2010
6:40 7 Nov '08  
When i try to demo this code . All control is define in .xslt is invisible in the browser . when i view source , i still see prefix asp
GeneralCan I use HTML Tags in the .config file
Prakash Koshti
1:55 30 Sep '08  
Hi
my requirement is to use HTML Tags such as

, ,

and so on.

Can we implement these too in our .config file along with ASP controls.

Thanks for your help.

- Prakash


Generalcode for WTMI.Collections needed [modified]
the bill
11:05 25 Sep '08  
Hi, is there anyone who would be kind enough to post the source for WTMI.Collections here?

wrote my own:

namespace WTMI.Collections
{
public class ObjectEntry
{
private string m_strName;
public string Name
{
get { return m_strName; }
set { m_strName = value; }
}
private string m_strValue;
public string Value
{
get { return m_strValue; }
set { m_strValue = value; }
}
public ObjectEntry()
{
}
public ObjectEntry(string strItemName, string strItemValue)
{
m_strName = strItemName;
m_strValue= strItemValue;
}
}

public class ObjectEntryCollection : CollectionBase
{
public int Add(ObjectEntry item)
{
return List.Add(item);
}
public void Insert(int index, ObjectEntry item)
{
List.Add(item);
}
public void Remove(ObjectEntry item)
{
List.Remove(item);
}
public bool Contains(ObjectEntry item)
{
return List.Contains(item);
}
public int IndexOf(ObjectEntry item)
{
return List.IndexOf(item);
}
public void CopyTo(ObjectEntry[] array, int index)
{
List.CopyTo(array, index);
}
public ObjectEntry this[int index]
{
get { return (ObjectEntry)List[index]; }
set { List[index] = value; }
}
}
}


modified on Thursday, September 25, 2008 4:23 PM

GeneralDeveloping a dynamic website using XML, XSL, C# and SQL Server
Member 984388
10:07 4 Aug '08  
I am looking for sample code to develop a dynamic form uisng XML using .Net, would some one has complete code? would you please email to jiansheng.zhu@usda.gov.

Thanks in advance
June
QuestionProblem with the output of this project
Will_FLBK
23:40 29 Jun '08  

After is the end of traduction of the XML
The project can't read the XML file, only the first part of the XSLT is read

GeneralNeeed working version for asp.net 2.0
krishnakonline
4:45 18 Jun '08  
Hi,

Pls. send me the code targeting asp.net 2.0. Thanks..
email: krishnak_reply@yahoo.com
GeneralHandling Events & Displaying data from database
Anne_mathew
22:06 12 Nov '07  
Hi please help me out in event handling...Also,I need to display data from database in the datagrid control generated dynamically.So how to generate On Load event? Is it possible to write script ?anyone has sample code on event handlingand displaying data plz do reply.

Sigh
QuestionEvent Handling
pawan venugopal
0:44 29 Aug '07  
hi all,

i Created a web form using XML.
how to add a events to controls which are generated dynamically.

GeneralHey all, I figured how to get events to fire
thisisavalidusername
5:33 25 Jul '07  
Hey all, I figured out how to get events to fire.

You need to declare a variable in your class to hold the control that fires the events. And yes, you need to do a FindControl to bind the variable to the actual control.

BUT HERE'S THE CATCH - You must do the FindControl AFTER these lines are executed :

Control ctrl = Page.ParseControl(result);
survey.Controls.Add(ctrl);

My guess is that they page doesn't "know" about the control until after you execute these lines. In any case, if you do things in this order, all of your events will fire as they should.

AnswerRe: Hey all, I figured how to get events to fire
Kr0d
17:48 24 Sep '08  
Nice, but here is how I did it which is more generic as it adds events to everything.

<pre>
[snip]  
            Dim ctrl1 As Control = Page.ParseControl(result1)
            form1.Controls.Add(ctrl1)
            sw.Close()

            recursiveAddEvents(form1.Controls)
[snip]



Sub recursiveAddEvents(ByRef controls As ControlCollection)
            For Each con As Control In controls
                  Try
                        If con.Controls.Count > 0 Then
                              recursiveAddEvents(con.Controls)
                        End If
                        Dim but As Button = CType(con, Button)
                        AddHandler but.Click, AddressOf ButtonClick
                  Catch ex As Exception
                        'dont worry, it just means its not a button.
                  End Try
            Next
      End Sub

      Protected Sub ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
            Dim clicker As Button = CType(sender, Button)
            MsgBox(clicker.Text)
      End Sub

</pre>

So ButtonClick will be called every time a button is clicked within form1

Enjoy

Glen
QuestionHandling Events
n8shadow
8:06 13 Jul '07  
does anybody know if its possible to add a server side script blocks like <script language="c#" runat="server"> void Page_Load(Object sender, EventArgs e){.. }</script> to ParseControl - so that the Eventhandling can be also in the xml or xsl?

Generalnot able to run..
vijaysaxena
1:49 2 Jul '07  
first i try by creating a new project and copy the project files but its giving error "xhtml1.0 transitional error.."

and i tried by creating new file and copied the code...
now i am getting error like file missing "default.config"
from where should i get this page..

GeneralThe XSLT code has little error.
V'ru
19:26 29 Apr '07  
Hi, the XSLT code has little error.
GeneralRe: The XSLT code has little error.
Terence Golla
7:39 4 Mar '10  
It would have been useful to post the errors...

<xsl:value-of select="FORM/PAGES/PAGE[@id=$pageid]/@title" />
corrected...
<xsl:value-of select="FORM/PAGES/PAGE[$pageid]/@title" />

<xsl:for-each select="FORM/PAGES/PAGE[@id=$pageid]/FIELDS/FIELD">
corrected...
<xsl:for-each select="FORM/PAGES/PAGE[$pageid]/FIELDS/FIELD">
GeneralParameter value not getting
V'ru
3:55 26 Apr '07  
Hi,
In above example , pageid parameter value is passed from .net 2.0. I have tried this code but I m not getting this parameter value. Plz solve problem.
AnswerRe: Parameter value not getting
KNet1
0:44 3 May '07  
place param definition
<xsl:param name="pageid"/>

before this line
<xsl:template match="/">


Last Updated 15 Oct 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010