Asp.Net : Convert Post Title into URL



Convert Post Title into URL

Hello Friends,
In these tutorials we see how to convert post title into url of page and display relevant data from Database.

Create Database


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

By using this page i'm going to insert data into database for that i'm simply adding three control as i shown in above image.

<%@ 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

C# Coding : 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;

C# Coding : Button Click


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);
    }

C# Coding : GenerateURL

    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;
    }
}

HTML Markup : Design Page

By Using this page i'm going to display data from 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

C# Coding : 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);
            }
        }
    }
}

C# Coding : Get Data From Database

    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

<%@ 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>      

Download URL Rewrite Project
Tag : ASP.NET, URL
0 Komentar untuk "Asp.Net : Convert Post Title into URL"

Back To Top