Asp.Net : Convert Post Title into URL

In this tutorial, we'll explore the process of converting a post title into a URL for a web page and how to display relevant data from a database. This technique is essential for creating user-friendly and SEO-friendly URLs on your website.

Convert Post Title into URL

Create Database

Let's start by creating a database to store our post data. We'll use Microsoft SQL Server for this example.


USE [master]
GO
/****** Object:  Table [dbo].[url]    Script Date: 06/15/2015 20:08:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[url](
 [id] [nchar](25) NOT NULL,
 [title] [nchar](150) NULL,
 [msg] [nvarchar](max) NULL
) ON [PRIMARY]
GO

HTML Markup: Design Page

We'll design a page to insert data into the database. The page includes input controls for the post title and message.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %>
<!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> URL Rewrite Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;">
        <h1>
            URL Rewrite Demo</h1>
    </div>
    <br />
    <div style="text-align: center;">
        <table>       
         <tr>
          <td>Title :</td>
          <td>&nbsp;<asp:TextBox ID="txt_title" runat="server" Width="382px"></asp:TextBox></td>
         </tr>
         <tr>
          <td>Message :</td>
          <td>&nbsp;<asp:TextBox ID="txt_msg" runat="server" Height="175px" Width="382px" 
                  TextMode="MultiLine"></asp:TextBox></td>
         </tr>
         <tr>
         <td><asp:Button ID="Btn_submit" runat="server" Text="Submit" 
                 onclick="Btn_submit_Click" /></td>
         </tr>
        </table>
    </div>
    </form>
</body>
</html>

C# Coding

Now, let's dive into the C# code to handle the button click event and generate a user-friendly URL.

Namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Text;

Button Click Event

public partial class _Default : System.Web.UI.Page
{   
    protected void Btn_submit_Click(object sender, EventArgs e)
    {
        DateTime time = DateTime.Now;             // Use current time.
        string format = "yyyyMMddHHmmssfff";   // Use this format.
        string bid = time.ToString(format); // Generate ID = (date+time+MilliSeconds) { its generate Unique Id }

        string connectionString = ConfigurationManager.ConnectionStrings["urlcon"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("Insert into url(id, title, msg) values('" + bid.ToString() + "','" + txt_title.Text.Trim() + "','" + txt_msg.Text + "')", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        string link = GenerateURL(txt_title.Text.Trim(), bid.ToString());
        Response.Redirect(link);
    }

GenerateURL Function

    private string GenerateURL(string title, string Id)
    {
        string strTitle = title.Trim();
        strTitle = strTitle.ToLower();
        strTitle = strTitle.Replace("c#", "c-sharp");
        strTitle = strTitle.Replace(" ", "-");
        strTitle = strTitle.Trim();
        strTitle = strTitle.Trim('-');
        strTitle = "~/Blogs/" + Id.ToString() + "/" + strTitle + ".aspx";

        return strTitle;
    }
}

Display Data from Database

We'll create another page to display the data from the database.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="page.aspx.cs" Inherits="page" %>

<!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>URL Rewrite Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;">
        <h1>
            URL Rewrite Demo</h1>
    </div>
    <br />
    <div style="width:700px;">
    <table style="width: 100%;">
       <tr>
       <td style="width:100px;"><b>Title :</b></td>
       <td style="width:500px;"><div id="divtitle" runat="server"></div></td>
       </tr>
       <tr>
       <td colspan="2">
        <div id="divmsg" runat="server" style="width:500px; height:auto; padding:10px;"></div>
       </td>
       </tr>
    </table>
    </div>
    </form>
</body>
</html>

C# Coding for Display Page

Namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

C# Coding: Page Load

public partial class page : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["id"] != null)
            {
                string id = Request.QueryString["id"].ToString();
                DisplayBlog(id);
            }
        }
    }
}

    private void DisplayBlog(string id)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["urlcon"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM url where id='" + id + "'", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            divtitle.InnerHtml = "" + ds.Tables[0].Rows[0]["title"].ToString() + "";
            divmsg.InnerHtml = ds.Tables[0].Rows[0]["msg"].ToString();
        }
    }

Global.aspx

To enable URL rewriting, add the following code to the Global.aspx file.


<%@ Application Language="C#" %>
<script runat="server">   
 protected void Application_BeginRequest(Object sender, EventArgs e)
  {
     HttpContext incoming = HttpContext.Current;
     string origionalpath = incoming.Request.Url.ToString();
     string subPath = string.Empty;
     string blogId = string.Empty;
     Int64 id = 0;
      if (origionalpath.Contains("Blogs"))
      {
       if (origionalpath.Length >= 37)
       {
        subPath = origionalpath.Substring(37);
        if (subPath.Length >= 1)
        {
         blogId = Regex.Match(subPath, @"\d+").Value;
         bool isValid = Int64.TryParse(blogId, out id);
         if (isValid)
         {
          incoming.RewritePath(String.Concat("~/URLRewriteDemo/page.aspx?id=", id.ToString()), false);
         }
       }
     }
   }
  }
</script>      

Post a Comment

0 Comments