|
Building a data driven web site and generating dynamic content is certainly commonplace with ASP. I’m going to show you how, with ASP.NET, you can move the dynamics to “before” the request, rather than “after”.
This article assumes you are familiar with the following:
With ASP you generate dynamic content by passing a parameter in the URL. Such as:
http://www.mydomain.com/page1.asp?id=57
where the parameter (in this case 57) would be the ID of the content in the database.
The asp page then contains the code to read the database, access the content and load the page accordingly.
With ASP.NET you can use a URL such as:
http://www.mydomain.com/57.aspx
by utilizing the HTTP Module provided in ASP.NET.
For this example I have created a new C# web application titled “MyApp”. First you add a new class to the web application for your HTTP Module. Copy and Paste the following code and name the file "MyModule.cs".
// begin MyModule.cs
namespace MyApp
{
using System;
using System.Web;
using System.Globalization;
using System.Threading;
using System.IO;
public class MyModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source, EventArgs e)
{
// Get abbreviated reference to current context
HttpContext Context = HttpContext.Current;
//url string
string requestPath = HttpContext.Current.Request.RawUrl;
//page requested
string pageName = GetPageName(requestPath);
//remove the extension, only want the page ID
pageName = pageName.Remove(pageName.LastIndexOf("."), 5);
//test if the page requested is an ID (numeral) page for the
//database, otherwise skip this and load the static page
if (IsNumeric(pageName))
{
Context.RewritePath("WebForm1.aspx?pageName=" + pageName);
}
}
// GetPageName Method
// get file name from url requested
public static string GetPageName(string requestPath)
{
if ( requestPath.IndexOf( '?' ) != -1 )
requestPath = requestPath.Substring( 0, requestPath.IndexOf( '?' ) );
return requestPath.Remove( 0, requestPath.LastIndexOf( "/" ) + 1);
}
// IsNumeric Method
// Since C# doesn't have an IsNumeric function, we have to use our own.
public static bool IsNumeric(string strInteger)
{
try
{
int intTemp = Int32.Parse( strInteger );
return true;
}
catch (FormatException)
{
return false;
}
}
// Dispose Method
// This method is required by the HttpModule Interface.
public void Dispose() {}
}
}
//end MyModule.cs |
After the creation of your HTTP Module class you then need to modify your web applications web.config file to use the HTTP Module. You will already have a this file in your project, simply insert the tag within
such as:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<httpModules>
<add name="MyModule"type="MyApp.MyModule, MyApp" />
</httpModules>
.
.
. |
After that all that’s left to do is put some code into the aspx page that you specified in the HTTP Module.
In this example I am using the default WebForm1.aspx. First I’ll open the
html view and add an asp label control. The label control will be the destination
of the content.
<asp:Label id="Label1" runat="server"></asp:Label> |
Next go to Code View for adding the processing code to the code-behind file. In my example I am using OLE DB and an Access database. If you are using an SQL database then modify the code accordingly.
First I need to add the Namespace for OLE DB
to the Namespaces already provided by default. Your aspx page should look like:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
.
.
. |
Next code the label in your page class:
namespace MyApp
{
///
/// Summary description for WebForm1.
///
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
.
.
. |
The final step is to add the “dynamics” to the Page_Load function. First we get the page being requested, then we create a connection, then create the query, then the command object, and we open the connection. Then use a data reader to read, assign the data to our string, close the reader and the connection and complete by assigning our string to the label.
private void Page_Load(object sender, System.EventArgs e)
{
string content = "";
string passedID = Context.Request.QueryString["pageName"];
OleDbConnection con = new OleDbConnection
("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" +
Server.MapPath("database/Catalog.mdb") + ";");
string strSelect = "Select ArticleText From Articles Where ArticleID = @ID";
OleDbCommand cmd = new OleDbCommand(strSelect, con);
cmd.Parameters.Add(new OleDbParameter("@ID", OleDbType.VarChar));
cmd.Parameters["@ID"].Value = passedID;
con.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
content = dr["ArticleText"].ToString();
}
dr.Close();
con.Close();
Label1.Text = content;
}
|
That is it. Build the application and test. You can then fill up your database with content and publish the web application files and you have yourself a dynamic web site.
© 2003 David
Bartosik. David is a Software Developer and Web Site Designer. He has been a Microsoft MVP for Publisher since 2001. You can learn more about Web design
and Publisher by visiting his site at davidbartosik.com.
David is also the Editor of BARVIN, a motivational and self-improvement site.
He invites you to visit at barvin.com. You can contact him at
dbtech@davidbartosik.com.
|