SEO friendly URl in asp.net

1.5k views Asked by At

Im creating a web application. There are a default page where a list of questions. When user click the question that will redirect to the user to ViewQuestion that is in the Question folder. At the default.aspx page im using the datalist control to display question title . And there i am generating the url with id to the question . For this code is below .

 protected void listQuestion_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
                 e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LinkButton lnkTitle = (LinkButton)e.Item.FindControl("lnkQuestion");
            // lnkTitle.Style.Add("text-decoration", "none");
            PostEntity Item = (PostEntity)e.Item.DataItem;
            lnkTitle.PostBackUrl = GenerateURL(Item.Title, Item.Id);
        }
    }

    public static string GenerateURL(string title, int Id)
    {
        string strTitle = title.Trim();
        strTitle = strTitle.ToLower();
        //strTitle = strTitle.Replace();
        strTitle = strTitle.Replace(" ", "-");
        strTitle = strTitle.Trim();
        strTitle = strTitle.Trim('-');
        strTitle = "~/Questions/ViewQuestion.aspx?QuestionID=" + Id.ToString().Trim() + "/" + strTitle + ".aspx";

        return strTitle;
    }

in global.asax the code is

void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        RegisterRoute(RouteTable.Routes);

    }

    static void RegisterRoute(RouteCollection route)
    {
        route.MapPageRoute("Default", "Default", "~/Default.aspx");
        route.MapPageRoute("ViewQuestion", "Questions/ViewQuestion{QuestionID}", "~/Questions/ViewQuestion.aspx");
    }

And the viewpage to get the Querystring as below :

lblQustionText.Text = this.Page.RouteData.Values["QuestionID"].ToString() as string; // giving me object reference exception 

my pageurl is generating like this

/Questions/ViewQuestion.aspx?QuestionID=1376/get-the-current-logged.aspx

How can i make this example for SEO friendly url . Thanks for your answer.

1

There are 1 answers

2
Paul-Jan On BEST ANSWER

There are two things about your code that seem to be wrong:

  1. Your page route should probably include a forward slash between the page name (ViewQuestion) and the question ID:

    Questions/ViewQuestion/{QuestionID}

  2. The page URL you generate does not match the route, it should not contain the aspx suffix and the order of the route parameter and the query parameter is mixed up. It should be something like

    String.Format("~/Questions/ViewQuestion/{0}?QuestionID={1}", strTitle, Id.ToString().Trim())

As a sidenote, I find it a bit confusing that you include a query parameter with the exact same name as your route parameter. My advice would be to use a route parameter for both, stackoverflow-style:

/Questions/ViewQuestion/numerical-id/question-description