I recently decided to implement Friendly URLs on my site in a bid to follow recent trends. What I wanted was to remove character spaces denoted by %20 and replace them with hyphens (-). Using Server.UrlEncode simply changes the character spaces appearing in the web browser address bar to a positive sign (+).
Dynamic URL
http://macocz-design.com/Post.aspx?title=Impementing%20Friendly%20URLs
Server.UrlEncode method
http://macocz-design.com/Post.aspx?Title=Implementing+Friendly+URLs
Friendly URL
http://macocz-design.com/post.aspx?title=implementing-friendly-urls
Right click the App_Code folder > Add New Item>Class.vb
Choose appropriate name like FriendlyUrl and the language VB.
Copy and paste the following code:
Public Class FriendlyUrl
Public Shared Function GenerateUrl(ByVal strTitle As String) As String
strTitle = strTitle.Trim()
strTitle = strTitle.Trim("-"c)
strTitle = strTitle.ToLower()
Dim chars As Char() = "$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray()
strTitle = strTitle.Replace("c#", "C-Sharp")
strTitle = strTitle.Replace("vb.net", "VB-Net")
strTitle = strTitle.Replace("asp.net", "Asp-Net")
strTitle = strTitle.Replace(".", "-")
For i As Integer = 0 To chars.Length - 1
Dim strChar As String = chars.GetValue(i).ToString()
If strTitle.Contains(strChar) Then
strTitle = strTitle.Replace(strChar, String.Empty)
End If
Next
strTitle = strTitle.Replace(" ", "-")
strTitle = strTitle.Trim()
strTitle = strTitle.Trim("-"c)
Return strTitle
End Function
End Class
Call the Function:
<%#FriendlyUrl.GenerateUrl(Container.DataItem("Title")) %>