Search code examples
c#asp.neturlurl-rewritingrepeater

Dynamically generating friendly URL and render the content from SQL db in unique page for all posts clicked in Asp.Net C#


As I am constructing a blog section in my website I would like to know how to render each of the blog post in unique page template or say view. I do not want to create aspx manually and then naming them with headings SEO.

Step 1 : I have created a table where it can totally store all the details, including image, content, heading and I am able to retrieve these values to bind it further in the repeater. Working fine

Step 2: However, Now next thing is,there is blog details page which will be displayed when clicked on any of the blogs, but will it bear the different URL as to match with the heading ?

Assume currently URL is www.xyz.com/blog/blogdeatils.aspx and if it is rendering a article which talks about wikipedia then I want my URL to be www.xyz.com/blog/how-wikipedia-works (no aspx extension)

Is this possible ? Thank you all


Solution

  • This has been called as "routing". Add Global.asax to your project and next is just an example of your file:

    <%@ Application Language="C#" %>
    <%@ Import Namespace="System.Web.Routing" %>
    
    
    <script runat="server">
    
    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    
    }
    
    void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("Article", "blog/{name}", "~/BlogDetails.aspx");
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
    
    }
    
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
    
    }
    
    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started
    
    }
    
    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
    
    }
    

    And in your BlogDetails.aspx you may use next code to fetch the title of the article:

    string article_name = Page.RouteData.Values["name"] == null ? "No article" : Page.RouteData.Values["name"].ToString();
    

    And then use this for retrieving information from a database.