Reputation: 17
I want to add '-' or '+' in between words in url. For example url like:
http://localhost/bollywood/details/23-abhishek-back-from-dubai-holiday.htm
My Route Pattern is
routes.MapRoute(
name: "AddExtension",
url: "{controller}/{action}/{id}-{title}.htm",
defaults: new { controller = "Bollywood", action = "Details" }
);
I am creating a link like this on my View:
@Html.ActionLink(item.n_headline, "Details", new { id = item.News_ID, title = item.n_headline.ToSeoUrl() }, htmlAttributes: null)
My Bollywood controller is here
public ActionResult Details(int? id, string controller, string action, string title)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
tblBollywood tblbolly = db.tblBollywood.Find(id);
if (tblbollywood == null)
{
return HttpNotFound();
}
return View(tblbollywood);
}
Upvotes: 1
Views: 1428
Reputation: 10824
you can use this method ;
public static string ToSeoUrl(this string url)
{
// make the url lowercase
string encodedUrl = (url ?? "").ToLower();
// replace & with and
encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");
// remove characters
encodedUrl = encodedUrl.Replace("'", "");
// remove invalid characters
encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9-\u0600-\u06FF]", "-");
// remove duplicates
encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");
// trim leading & trailing characters
encodedUrl = encodedUrl.Trim('-');
return encodedUrl;
}
then you can use this way :
@Html.ActionLink(item.Name, actionName: "Category", controllerName: "Product", routeValues: new { Id = item.Id, productName = item.Name.ToSeoUrl() }, htmlAttributes: null)
Edit :
you need to create a new custom route :
routes.MapRoute(
"Page",
"{controller}/{action}/{id}-{pagename}.htm",
new { controller = "Home", action = "Contact" }
);
then use ActionLink this way :
@Html.ActionLink("link text", actionName: "Contact", controllerName: "Home", routeValues: new { Id = item.id, pagename = item.heading.ToSeoUrl() }, htmlAttributes: null)
Upvotes: 3