I have a problem like this. In RouteConfig.cs, I set routes
routes.MapRoute(
"NewsDetails",
"news/details-news/{title}-{id}",
new { controller = "News", action = "Details", id = "", title = "" }
);
In my Index.cshtml of NewsController I have a link
@Html.RouteLink(item.Title, "NewsDetails", new {
title = MyWeb.Classes.PrettyUrlHelper.PrettyUrl(item.Title),
id = item.Id
})
In my NewsController:
public ActionResult Details(string title,String id)
{
if (id == null && title == null)
return RedirectToAction("Index");
try
{
int ID = Int32.Parse(id);
var result = NewsConnectionDB.GetInstance().Single<LifeStory>(ID);
return View(result);
}
catch (InvalidOperationException) {
return View("~/Views/Error/Error404.cshtml");
}
catch (FormatException) {
return View("~/Views/Error/Error404.cshtml"); }
}
So if a user click on link in View, that link will route to action Details to process, and the link is Seo Url Friendly (localhost:9224/news/details-news/ten-things-2). But a user types a link instead of clicking to a link in View:
localhost:9224/news/details-news/ten-thingsblahblahblah-2
The url above is correct with id but title is not. So how can I update the url after I return View if a user types the wrong title but right id?
Any help would be appreciated.
P/S: my English is not good, so I hope you understand it.
2
Answers
If title is incorrect then you can send correct url in response headers. If it’s ajax call then on completion check for correct url in response header. If correct url exists then change your browser url using
window.history.pushState
javascript method.In Details action method use below code to set response header.
Use HttpServerUtility.UrlEncode(string);
javascript code can be replace url, I think it will be working :).
C# code
script code
or C# code redirect url
Update
possible 1 solution with Context.RewritePath
It code is example, You can use it
I hope it help