Reputation: 85
I am trying to make my websites urls more SEO friendly, so I Used This approach to change routing.(although I don't know is this approach is Best Way or not - but this is not my Question!)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "interface",
url: "soal/{id}/{slug}", /* "soal" is only decor */
defaults:new { controller = "ui", action = "singleQuestion",
slug = UrlParameter.Optional} /*I made "slug" optional because I don't need this part to retrieve conternt from database */
/* slug only explains content of the webpage*/
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
This Is The "SingleQuestion" Action that Processes pages:
public ActionResult singleQuestion(int id, string slug)
/* "slug" parameter here does nothing. Action Does not use this.*/
{
var questions = BQcnt.Questions;
var showQuestion = questions.Find(id);
if (showQuestion != null)
{
var AnswerOfShowQuestion = BQcnt.Answers.Where(
i => i.QuestionID == showQuestion.QuestionID);
ViewBag.lastQuestion = showQuestion;
ViewBag.answer_of_show_question = AnswerOfShowQuestion;
}
return View(questions.OrderByDescending(x => x.QuestionID));
}
well this works fine when i use these Urls:
http://localhost:9408/soal/13/bla-bla-bla
and
http://localhost:9408/soal/13
these urls direct to same pages But My only problem is this: when I use second url, I want when page loads automatically URL changes to Complete One and the slug append to the url, Like first One.
edit: I want some thing exactly Like stackoverflow.com urls. these two urls:
http://stackoverflow.com/questions/34615538/how-to-make-url-in-mvc-5-seo-friendly-and-consistent
http://stackoverflow.com/questions/34615538
opens same page, But when we use second one(as you can examine ) url translates to first one automatically. but my urls does not translate like this.
Upvotes: 3
Views: 2200
Reputation: 85
ok, the problem solved by myself.
public ActionResult singleQuestion(int id, string slug)
{
var questions = BQcnt.Questions;
var showQuestion = questions.Find(id);
if (showQuestion != null)
{
var AnswerOfShowQuestion = BQcnt.Answers.Where(
i => i.QuestionID == showQuestion.QuestionID);
ViewBag.lastQuestion = showQuestion;
ViewBag.answer_of_show_question = AnswerOfShowQuestion;
if (slug != showQuestion.slug)
{
return RedirectToAction("singleQuestion", new { id = id, slug = showQuestion.slug });
}
else
{
return View(questions.OrderByDescending(x => x.QuestionID));
}
}
return RedirectToAction("Index");
}
maybe it,s dirty... but perfectly works...
Upvotes: 3