How to create ASPX Page Dynamically - A Step Ahead Series?


In these days dynamic content creation and rendering pages dynamically is on demand. I will explain in this whole article how we can create dynamically pages in asp.net. Dynamically means fully handled with events and code-behind. So, lets try it

Introduction


In a simple creating an aspx page dynamically is a very tedious job. Whenever we think for dynamically creation scenarios stuck in mind about the overload to server etc. But with the help of this article one can attain the same as easily as creating another simple aspx page.

Need and Requirement


Now next words came to mind that what is the need to create an aspx page dynamically? Let me explain it:


  1. You need to create a page, based on selected requirement at the moment.

  2. Need to create a page from static html contents.

  3. Having huge data, need to represent in an individual page and its tough to store in database.



Article Scenario


As stated above, I choose a scenario where you are running a technical community and need to the template where member of your site will able to write some static html contents.

Explanation


For the same we need following pages:
1.PageHeader.ascx
This contains the header information of your page like LOGO etc.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PageHeader.ascx.cs" Inherits="myTemplates_PageHeader" %>
<link href="../style.css" rel="stylesheet" type="text/css" />
<div>
<asp:PlaceHolder ID ="plhImage" runat="server" />
<ul class="menu">
<li><a href="./default.aspx">HOME</a></li>
<li><a href="./default.aspx">About US</a></li>
<li><a href="./default.aspx">Recent Posts</a></li>
<li><a href="./default.aspx">Site Map</a></li>
<li><a href="./default.aspx">Contact US</a></li>
<li><a href="./default.aspx">Tags</a></li>
<li><a href="./default.aspx">Meta</a></li>
<li><a href="./default.aspx">Most Emailed</a></li>
</ul>
</div>




2.PageFooter.ascx
Obvious it contains the Footer information.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PageFooter.ascx.cs" Inherits="myTemplates_PageFooter" %>
<link href="../style.css" rel="stylesheet" type="text/css" />
<div id="footer">
<div>
<a href="http://www.webdesign.org">Web Design</a> by <a href="http://www.freetemplatesonline.com">Free Templates</a> Online<br />
<a href="#">Terms of Use</a> / <a href="#">Privacy Policy</a>
</div>
<div class="centeral-block">
<strong>New-York, USA</strong>
11 Some Street Second Floor<br /> New York WA 02020
</div>
<div>
Tel/Fax : 1(800)123-4567<br />
1(800)123-1234<br />
E-mail : <a href="#" id="mail">info@yourcompany.com</a>
</div>
</div>




3.createPage.ascx
Definitely this is the main page, it just create a skeleton as per the above requirement and then segregate the contents and make the title.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="createPage.ascx.cs" Inherits="myTemplates_createPage" %>
<div>
<table>
<tr>
<td style="width: 100px">
Page Title
</td>
<td style="width: 100px">
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
Tags
</td>
<td style="width: 100px">
<asp:TextBox ID="txtTags" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
Description
</td>
<td style="width: 100px">
<asp:TextBox ID="txtContent" runat="server" Height="292px" TextMode="MultiLine" Width="510px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100%">
<ul>
<li><font color="red">You may use basic html tags like <H1> <H2> <B>
<I> <FONT> etc. </font></li>
<li><font color="red">Tags like <BODY> <HEAD> <TABLE> are NOT allowed.</font></li>
<li><font color="red">Please check spelling before posting articles.</font></li>
</ul>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100%">
<asp:LinkButton ID="lnkNewPage" OnClick="lnkNewPage_Click" runat="server"></asp:LinkButton>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
<asp:Button ID="btnGenerate" runat="server" OnClick="btnGenerate_Click" Text="Generate" />
</td>
</tr>
</table>
</div>




4.Default.aspx
This is the page or container which contains above all 3-controls.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %>

<%@ Register TagPrefix="myPage" TagName="aspxPage" Src="~/myTemplates/createPage.ascx" %>
<%@ Register TagPrefix="myPageHeader" TagName="PgHeader" Src="~/myTemplates/PageHeader.ascx" %>
<%@ Register TagPrefix="myPageFooter" TagName="PgFooter" Src="~/myTemplates/PageFooter.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td colspan="2">
<myPageHeader:PgHeader ID="PgHeader1" runat="server" />
</td>
</tr>
<tr>
<td>
<h2>
Create Dynamic Page(S)</h2>
</td>
</tr>
<tr>
<td colspan="2">
<myPage:aspxPage ID="asxPage1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<myPageFooter:PgFooter ID="PgFooter1" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



5.myPageTemplate.tmp
This is the template page for all pages


<%@ Page Language="C#" CodeFileBaseClass="PageBase" AutoEventWireup="true" CodeFile ="myPageCode.cs"
Inherits= "myPageCode" PageID="[ID]" MetaTitle="[MetaTitle]" MetaKeywords="[MetaKeywords]" %>
<%@ Register TagPrefix="myPageHeader" TagName="PgHeader" Src="~/myTemplates/PageHeader.ascx" %>
<%@ Register TagPrefix="myPageFooter" TagName="PgFooter" Src="~/myTemplates/PageFooter.ascx" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%">
<tr>
<td colspan="2">
<myPageHeader:PgHeader ID="PgHeader1" runat="server" />
</td>
</tr>
<tr>
<td>
<h2>
<%=MetaTitle%></h2>
</td>
</tr>
<tr class=content>
<td colspan="2">
[PageContent]
</td>
</tr>
<tr>
<td colspan="2">
<myPageFooter:PgFooter ID="PgFooter1" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>



6.myPageCode.cs
A common code-behind page for all dynamic pages


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class myPageCode : PageBase
{
public String newPageID
{
get
{
if (ViewState["newPageID"] != null)
return Convert.ToString(ViewState["newPageID"]);
else
return "0";
}
set
{
ViewState["newPageID"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
base.PageID = this.newPageID;
}

}


7.PageBase.cs
A pagebase which inherits System.Web.UI.Page.


using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

///
/// Summary description for PageBase
///

public class PageBase : System.Web.UI.Page
{
public PageBase()
{
//
// TODO: Add constructor logic here
//
}
#region Properties
public String PageID
{
get
{
if (ViewState["PageID"] != null)
return Convert.ToString(ViewState["PageID"]);
else
return "0";
}
set
{
ViewState["PageID"] = value;
}
}
public String MetaTitle
{
get
{
if (ViewState["MetaTitle"] != null)
return Convert.ToString(ViewState["MetaTitle"]);
else
return "No Title";
}
set
{
ViewState["MetaTitle"] = value;
}
}
public String MetaKeywords
{
get
{
if (ViewState["MetaKeywords"] != null)
return Convert.ToString(ViewState["MetaKeywords"]);
else
return "No Keywords";
}
set
{
ViewState["MetaKeywords"] = value;
}
}
#endregion

protected override void OnLoad(EventArgs e)
{
if (!String.IsNullOrEmpty(MetaTitle))
{
HtmlMeta Title = new HtmlMeta();
Title.Name = "Title";
Title.Content = this.MetaTitle;
this.Header.Controls.Add(Title);
}

if (!String.IsNullOrEmpty(MetaKeywords))
{
HtmlMeta Keyword = new HtmlMeta();
Keyword.Name = "Keywords";
Keyword.Content = this.MetaKeywords;
this.Header.Controls.Add(Keyword);
}

//overide base
base.OnLoad(e);
}

void Page_Error(object sender, EventArgs e)
{
//Write Some logic here
}
}



Important



  1. Please note that I don't check for any validation
  2. Instead of the use of Custom Control you can use Master Pages too.

  3. The same will create a good facility while you need to create dynamic pages.



How to run attached code:

1.Download the zip file
2.Open your Visual Studio2008
3.Open WebProject select the specific folder
4.Press F5 and enjoy

Your suggestions are invited to improve this.


Attachments

  • Dynamic Pages (26301-22126-DynamicPages.rar)
  • Article by Gaurav Aroraa
    Gaurav is a Microsoft Technology Specialist professional. He has awarded lifetime membership from Computer Society of India (CSI). He has more than 13yrs of experience in the industry. Currently, he is working in the capacity of Solution Architect with an MNC. He is serving to the various communities since 1999.

    Follow Gaurav Aroraa or read 149 articles authored by Gaurav Aroraa

    Comments

    Author: Pandu (srini)18 Jul 2009 Member Level: Gold   Points : 1

    HI,

    I download the Zip file,and I Executed,but i got error

    The virtual path '/myPages/myDefaultPage.ascx' maps to another application, which is not allowed.
    what i need to do for successfylly run
    i hope u will back with solution

    Author: Gaurav Aroraa18 Jul 2009 Member Level: Gold   Points : 0

    Hi Pandu,
    You have to set your own virtual path. You can set this as per your convenience from your own machine or other servers.

    Author: Viji RAJKUMAR28 Jul 2009 Member Level: Gold   Points : 1

    Hi Gaurav

    Good presentation!!!It deserves more than a 10.

    Author: nagaraju19 Nov 2009 Member Level: Bronze   Points : 1

    While I am runing the project, It is not showing any out put when I am clinking on Generate Button.

    I am using .net2.0 frame work

    Author: nagaraju19 Nov 2009 Member Level: Bronze   Points : 1

    While I am runing the project, It is not showing any out put when I am clinking on Generate Button.

    I am using .net2.0 frame work

    Author: nishithraj24 Nov 2009 Member Level: Gold   Points : 1

    Gaurav,

    Good article... Keep this up....

    The way you presented is really inspiring.

    Author: narendra25 Aug 2010 Member Level: Bronze   Points : 1

    Thanks for this nice article, i have some problem i want to read the dynamically created pages, could you plz tell me how can i access pages and i want to dynamically add record from database like 40 record in each page so plz tell me how can i achieve these...

    Guest Author: kakashi19 Jan 2012

    My name is kakashi. Iam new to this programming . Can you explain me why base class is used in this entire task . Without that base class will it work? If not why it will not work?

    Author: Gaurav Aroraa17 May 2012 Member Level: Gold   Points : 2

    Hi Kakashi,

    Hope you have already downloaded the attached project and gone through the same.

    Did you notice, BaseClass is having controls over other pages, means it contains PageId which refer to individual dynamically generated page.

    The answer for your question as off now [per above example] it will not run without this page-class. There are other option like Asbtarction we can use the same to make BaseClass as redundant.

    If you still have any query, you can reach me

    Author: Gaurav Aroraa19 May 2012 Member Level: Gold   Points : 1

    Hey Narendra,

    Sorry I missed to reply your query.
    Can you elaborate what do you mean from Read Dynamically pages.
    As per example shown in this article, you can do get records from DB. Even you can store your dynamic contents in DB and later on you can get through one base page-class.

    If you give me a full query, it helpful to me to present some demo application for the same.

    Guest Author: MANJUNATH02 Nov 2012

    Good One Sir..THanks

    Guest Author: dhruv16 Jan 2013

    nice article sir...really helpful..
    but when I applied this on my web portal i get excluded pages in my directory..please guide me that what to do to get include page...

    hoping for your reply

    Guest Author: raheel27 Dec 2013

    Its gives error I am new on ASp.net
    error1:ViewState doesn't exist in current content
    error2:Does not contain a definition of pageID

    Author: Gaurav Aroraa20 Apr 2014 Member Level: Gold   Points : 3

    Receiving many emails for the above code and attachment.
    Please note that this is a bit older code/concept, written in C# using Visual Studio 2008. The new version will be available very soon, including MVC4/MVC5 support. If anyone is having any trouble to download the attachment, can get from GitHub under link: https://github.com/garora/somestuff/tree/master/MyStuff/Older/DynamicPages

    Author: Gaurav Aroraa20 Apr 2014 Member Level: Gold   Points : 0

    @Raheel - I am not getting such errors, can you download the source code from GitHub and try again. Just in case, you will face any issue, provide whole stack trace.

    Author: Shuby Arora28 Apr 2015 Member Level: Gold   Points : 0

    Good explanation. Can we get code in mvc5?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: