Generate Dynamic Title Tag based on QueryString in ASP.NET 3.5

The title tag is one of the most important HTML elements of any web page. Not only does it guide your website visitors to appropriate content, but having a unique and relevant title tag is useful for search engine optimization purposes. This article will illustrate how to generate unique title tags for any ASP.NET 3.5 web page that uses a QueryString in the URL.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 6
July 07, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

If you're not sure what is meant by a QueryString, here is an example: http://localhost:4394/titletagquerystring/Details.aspx?id=1 is a URL that uses a QueryString with its id set to "1."

It is a common practice to use a QueryString in the URLs, particularly in ASP.NET 3.5 websites that depend strongly on an MS SQL Server database to retrieve content and then display it on the browser.

If you are not familiar with creating dynamic websites using QueryString in ASP.NET 3.5, you will want to read the tutorial at the link before going any further in this article.  

The process of generating a dynamic title

You will need to replicate/create the project discussed in this basic QueryString tutorial in your own Visual Web Developer Express platform. This will be used as an example project for this tutorial on generating dynamic title tags. For consistency with the code discussed throughout this tutorial, you need to name your project titletagquerystring.

Once you have loaded the files and the database, go to Default.aspx and then File -> View in Browser. If you click on the "Read Details" hyperlink to take you to the aircraft details page, you might notice that the pages does not use a title tag. Instead, the URL is displayed by default. In this case, the title tag displayed by the browser is: http://localhost:1438/aspnetqueryurl/Details.aspx?id=2. This is not the correct title; and when you examine the HTML source code, the title tag element is empty in the head section:

<
head><
title></
title></
head>
 

The solution is to use the URL's query string to get title tag information from the SQL server database. This process is explained below.

Step 1: User clicks the link to the detailed page from Default.apsx (home page).

Step 2: The detailed page uses a QueryString, and will trigger the page load event, which will execute the server side script (using VB.NET) to get the id value of the query string. For example, if id =3, then 3 is parsed.

Step 3: Visual Basic will connect to the MS SQL Server database.

Step 4: An SQL query will be executed on the MS SQL Server database based on VB.NET query input. This SQL query will retrieve the name of the aircraft based on the id (parsed from the QueryString). For example, when id =2, the aircraft name to be retrieved is "B-52 Stratofortress."

Step 5: The ME SQL query returns the aircraft name's value to VB.NET, which then displays the output (aircraft name) to the page title tag element at the browser.

So when the id is changed to something (for example, if the visitor clicks on  another aircraft details page), the steps above will be repeated, and the SQL server will return the equivalent aircraft name based on the value of the query string id.

Editing the title tag element in Details.aspx

Since Default.aspx is not dynamically driven by query ids (there is no editing required for Default.aspx), you will only be editing the source code of Details.aspx and its associated VB.NET source code: Details.aspx.vb

When you go to the source code view of Details.aspx using Visual Web Developer, the current the title tag is empty, so you will replace the title tag, changing it from this:

<title> </title>

To this:

<title id="titletag_output_from_VB" runat="server"></title>

This will cause the title tag to be dynamically driven by the VB.NET output (which communicates with the MS SQL Server database to fetch title tag information).

In the Visual Basic code, whose details will be discussed in the next section), you will output the text to the HTML by:

titletag_output_from_VB.Text = nameofaircraft

 

Where:

 

Titletag_output_from_VB is the ID name of the title tag element in the Details.aspx.

 

So the name of the aircraft is basically assigned to Titletag_output_from_VB Id, which in return displays it on the browser. Details of the process are shown in the example below:

 

 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Details.aspx.vb" Inherits="Details" %>

 

<!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 id="titletag_output_from_VB" runat="server"></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

            SelectCommand="SELECT * FROM [aircrafttable] WHERE ([aircraftid] = @aircraftid)">

            <SelectParameters>

                <asp:QueryStringParameter Name="aircraftid" QueryStringField="id"

                    Type="Int32" />

            </SelectParameters>

        </asp:SqlDataSource>

        <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"

            AutoGenerateRows="False" DataKeyNames="aircraftid"

            DataSourceID="SqlDataSource1">

            <Fields>

                <asp:BoundField DataField="name" HeaderText="Aircraft Name"

                    SortExpression="name" />

                <asp:BoundField DataField="type" HeaderText="Aircraft type"

                    SortExpression="type" />

                <asp:BoundField DataField="primaryuser" HeaderText="Primary User"

                    SortExpression="primaryuser" />

                <asp:ImageField DataImageUrlField="aircraftid"

                    DataImageUrlFormatString="/titletagquerystring/aircraftimages/{0}.jpg"

                    HeaderText="Photos">

                </asp:ImageField>

            </Fields>

        </asp:DetailsView>

    </div>

    </form>

</body>

</html> 

Page load event and VB.NET script to process QueryString

You need to create a page load event in VB.NET. If you are new to creating page load events, you need to read this tutorial on event handlers

The page load event handler is usually indicated by (using VB.NET):

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

 

So how are you going to write the complete Details.aspx.vb script? The following are the important steps you need to undertake. A complete Details.aspx.vb script will be available in the last section of this tutorial.

Step 1. Since you are communicating and working with an MS SQL Server database, you need to declare a namespace at the top of the Details.aspx.vb code:

Imports System.Data.SqlClient

Imports System.Data.SqlClient

, you will then see:

Partial Class Details

    Inherits System.Web.UI.Page

 

And next is the page load event handler:

 

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

 

Within this handler you will declare your VB.NET variables and the connection details to the SQL Server database.

Step 3. Just below the page load event handler, you will need to declare the VB.NET variable which holds the value of the URL query string id.

Dim queryid As Integer

It is declared as integer because the id uses integers: 1, 2, 3, 4, and so on.

Step4.  Now the variable is declared and ready to use in your VB code, so you can parse the QueryString id from the URL using:

queryid = Request.QueryString("id")

 

So if the URL is:  http://localhost:4394/titletagquerystring/Details.aspx?id=6

The value of queryid is 6.

Dim myCommand As SqlCommand = New SqlCommand()

Step 6. Define your SQL server connection parameter:

New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|
militaryaircraft.mdf;Integrated Security=True;User Instance=True"
)

Data Source = with your own connection details.

Step 7. Open the database connection:

myCommand.Connection.Open()

 

Step8. Define your SQL query (this query will retrieve the aircraft name in the database based on queryid variable)

myCommand.CommandText = "SELECT name FROM aircrafttable WHERE aircraftid=" & queryid

 

Note that the queryid variable is "concatenated" using the "&" symbol with the SQL query syntax.

Step 9. Execute the query and assign the results to the nameofaircraft VB.NET variable (details already discussed in the previous section).

Dim retrievevalue As SqlDataReader = myCommand.ExecuteReader()

While retrievevalue.Read()

Dim nameofaircraft As String = CStr(retrievevalue("name"))

    titletag_output_from_VB.Text = nameofaircraft

End While

 

Step 10. Close the query execution:

 

retrievevalue.Close()

 

Step 11.  Close the database connection:  

 

myCommand.Connection.Close()

 

Final Details.aspx.vb source code

 

Based on the discussion in the previous section, below is the final VB.NET source code for Details.aspx.vb that will get the query string id from the URL, and then retrieve the equivalent aircraft name from the SQL Server database based on the query string id:

Imports System.Data.SqlClient

Partial Class Details

    Inherits System.Web.UI.Page

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim queryid As Integer

        queryid = Request.QueryString("id")

        Dim myCommand As SqlCommand = New SqlCommand()

        myCommand.Connection = New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|
militaryaircraft.mdf;Integrated Security=True;User Instance=True"
)

        myCommand.Connection.Open()

        myCommand.CommandText = "SELECT name FROM aircrafttable WHERE aircraftid=" & queryid

        Dim retrievevalue As SqlDataReader = myCommand.ExecuteReader()

        While retrievevalue.Read()

            Dim nameofaircraft As String = CStr(retrievevalue("name"))

            titletag_output_from_VB.Text = nameofaircraft

        End While

        retrievevalue.Close()

        myCommand.Connection.Close()

    End Sub

End Class

 

So when any aircraft details page is viewed and loaded, the title tag will now use the aircraft's exact name. See the screen shot below (inside the red box):

 

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials