Dynamically Creating .ASPX Page during Runtime in asp.net?


Creating ASPX Page Dynamically in ASP.Net

There are situations where we need to create ASPX pages dynamically in our asp.net websites. For example, if we want to build a tutorial hosting site or a content management system that has huge static data, we can publish it as a static pages instead of putting it into database. With static pages, we can save database memory with performance improvement because of its static nature. But, this approach will be tedious if we create aspx pages manually and copy it to the server everytime for publishing new information.

This article will give you an idea on how to handle this scenario and create aspx dynamically.

Consider we are building an article hosting site. The pages that are hosting the article will have similar behavior i.e. it will have article content, a rating system, commenting system etc that is similar on every pages. Similar behavior means, the codebehind functionality is same for all pages. Keeping this in our mind, we will build a common codebehind class first and create the aspx markup file dynamically. We need to link the aspx page with the common codebehind class using Inherits and CodeFile attribute in @Page directive. To make the implementation simple, we will build a template aspx page with some placeholders for values. These placeholders can then be replaced with the actual values when creating aspx page dynamically. Refer the below Template ASPX page in “Template ASPX Page” section.

Moving forward, this article will help us to build aspx pages dynamically that have similar functionalities.

Creating Master Page
Our first step will be creating a MasterPage which gives common look and feel across pages. For simplicity purpose I have created a simple master page that has the logo on left hand side and a single ContentPlaceHolder for page contents.

<%@ Master Language=”C#” AutoEventWireup=”true” CodeFile=”MainMaster.master.cs” Inherits=”MainMaster” %>

 
Untitled Page

Your Site Logo

 

Our next step will be creating a template ASPX page that has the basic skeleton of the dynamic aspx pages.

Template ASPX Page
<%@ Page Language=”C#” MasterPageFile=”MainMaster.master” CodeFileBaseClass=”BasePage” AutoEventWireup=”true” CodeFile=”CommonCodeBehind.cs” Inherits=”CommonCodeBehind” PageID=”[ID]” Title=”[Title]” MetaKeywords=”[key]” MetaDescription=”[MetaDes]” %>

[PageContent]

If you see the above code, we are linking the codebehind class through Inherits and CodeFile attribute. There are placeholders that are defined in the template which should be replaced with actual values while creating the page. We have also defined PageID, MetaKeywords and MetaDescription custom attrbutes that is defined in BasePage class and is referenced via CodeFileBaseClass attribute. The meta keyword and description tags will be dynamically created in BasePage class based on the value set on the @Page directive.

Refer below for the BasePage class and common codebehind class.

BasePage.cs
public class BasePage : System.Web.UI.Page
{
private string _metadescription;
private string _metakeywords;
private string _ID;

public string MetaDescription
{
get
{
return _metadescription;
}
set
{
_metadescription = value;
}
}
public string MetaKeywords
{
get
{
return _metakeywords;
}
set
{
_metakeywords = value;
}
}
public string PageID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}

public BasePage()
{
//
// TODO: Add constructor logic here
//
}
protected override void OnLoad(EventArgs e)
{

if (!String.IsNullOrEmpty(MetaKeywords))
{
HtmlMeta tag = new HtmlMeta();
tag.Name = “keywords”;
tag.Content = MetaKeywords;
Header.Controls.Add(tag);
}

if (!String.IsNullOrEmpty(MetaDescription))
{
HtmlMeta tag = new HtmlMeta();
tag.Name = “description”;
tag.Content = MetaDescription;
Header.Controls.Add(tag);
}

base.OnLoad(e);
}
void Page_Error(object sender, EventArgs e)
{
Server.Transfer(“Error.aspx”);
}
}

CommonCodeBehind.cs
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 CommonCodeBehind : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
(Page.Master as MainMaster).PageID = this.PageID;
}
}

ASP.Net Hosting
WinHost – $4.95 ASP.NET Hosting & No Setup Fees!

Recent Articles
Exception/Error Logging in Asp.Net Using log4net – PART 2
By Bala Murugan
Exception/Error Logging in Asp.Net Using log4net-PART 1
By Bala Murugan
Upload Images and Integrate with CKeditor in Asp.Net
By Bala Murugan
Search Engine Optimization (SEO) Tips for ASP.Net Sites
By Bala Murugan
Highlight Input Controls when Validation fails in Asp.Net Validator controls
By Satheesh Babu B
As I said earlier, the page can have some functions like rating system, commenting system etc. These functionalities can be implemented in MasterPage itself. The PageID(or a ArticleID) in @Page Directive will help us identify the article for which the comment and rating should be stored in database. We can also implement these functionalities through a user control and can include it in the master page. The title that is set on the Title attribute can be assigned to lblPageHead in MasterPage.

Refer the below Codebehind file of the master page for clear understanding.

public partial class MainMaster : System.Web.UI.MasterPage
{
private string _pageID;

public string PageID
{
get
{
return _pageID;
}
set
{
_pageID = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
this.lblPageHead.Text =this.Page.Title;
}
}

The PageID value can be used to store the comments, ratings, etc from Master Page.

Dynamic ASPX Page Generation
We will build a page that accepts Title, Meta Keyword, Meta Description and Content from the user and replace it with the placeholders that are in Template.aspx page and save it as a separate aspx page. Refer the below diagram.

The dynamic page creation cod will be,

protected void btnCreate_Click(object sender, EventArgs e)
{
string root = Server.MapPath(“~”);
//Read the Template file
string Template = root + “\\PageTemplate.temp”;
StringBuilder line = new StringBuilder();
using (StreamReader rwOpenTemplate = new StreamReader(Template))
{
while (!rwOpenTemplate.EndOfStream)
{
line.Append(rwOpenTemplate.ReadToEnd());
}
}

int ID = 0;
string SaveFilePath = “”;
string SaveFileName = “”;
Random ran = new Random();
ID = ran.Next();

//Page Name Creator with only URL allowed character
string Title = ID.ToString() + “-” + StripURLNotAllowedChars(txtTitle.Text);
SaveFileName = “\\”+ Title + “.aspx”;
SaveFilePath = root + “\\Pages\\” + SaveFileName;
FileStream fsSave = File.Create(SaveFilePath);
if (line != null)
{ //Replace the page content
line.Replace(“[Title]”, txtTitle.Text.Replace(“<“, “<“).Replace(“>”, “>”).Replace(‘”‘, ‘ ‘).Replace(‘”‘, ‘ ‘));
line.Replace(“[PageContent]”, txtContent.Text);
line.Replace(“[MetaDes]”, txtDes.Text.Replace(‘”‘, ‘ ‘).Replace(‘”‘, ‘ ‘).Replace(‘<‘, ‘-‘).Replace(‘>’, ‘-‘) );
line.Replace(“[key]”, txtKey.Text.Replace(‘”‘, ‘ ‘).Replace(‘”‘, ‘ ‘).Replace(‘<‘, ‘-‘).Replace(‘>’, ‘-‘));
line.Replace(“[ID]”, ID.ToString());
StreamWriter sw = null;
try
{//write content
sw = new StreamWriter(fsSave);
sw.Write(line);
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
finally
{
sw.Close();
}
}
}
private string StripURLNotAllowedChars(string htmlString)
{
string pattern = @”\s|\#|\$|\&|\||\!|\@|\%|\^|\*|\<\|\>|\\|\/|\+|\-|\=”;
return Regex.Replace(htmlString, pattern, “-“);
}

In the above code, we are reading the template aspx markup from a file to a StringBuilder object “line”. You can choose your own way of handling this Template page i.e. you can also store in a table and retrieve it when necessary.
From the Title of the page that is typed in by the user we are creating the Page name. The Title that is inputted by user can have space and URL not allowed characters which should be replaced with a URL allowed characters like “-“. Thus, the page name itself will describe the content which is more search engine friendly. We can also append an ID which will make the page name unique and the same number can be used to identify the article/page in database to store comments, ratings, etc.
Finally, all the placeholders should be replaced with the user contents and values.
For example, [Title] with the text of “txtTitle” TextBox that is typed in by the user.

This approach can be used as an example and we can refine it further to fit to our need and also we can improve it further for better performance.
Source:
Click Here

Sample 2
Sample 3

OPEN SOURCE .NET BLOGS & CMS
Happy coding…!

Advertisements

4 thoughts on “Dynamically Creating .ASPX Page during Runtime in asp.net?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s