我想在网址中的单词之间添加' - '或'+'。例如url:
http://localhost/bollywood/details/23-abhishek-back-from-dubai-holiday.htm
我的路线模式是
routes.MapRoute(
name: "AddExtension",
url: "{controller}/{action}/{id}-{title}.htm",
defaults: new { controller = "Bollywood", action = "Details" }
);
我在我的视图中创建了这样的链接:
@Html.ActionLink(item.n_headline, "Details", new { id = item.News_ID, title = item.n_headline.ToSeoUrl() }, htmlAttributes: null)
我的宝莱坞控制器就在这里
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);
}
答案 0 :(得分:3)
你可以使用这种方法;
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;
}
然后你可以用这种方式:
@Html.ActionLink(item.Name, actionName: "Category", controllerName: "Product", routeValues: new { Id = item.Id, productName = item.Name.ToSeoUrl() }, htmlAttributes: null)
修改:
您需要创建新的自定义路线:
routes.MapRoute(
"Page",
"{controller}/{action}/{id}-{pagename}.htm",
new { controller = "Home", action = "Contact" }
);
然后以这种方式使用ActionLink:
@Html.ActionLink("link text", actionName: "Contact", controllerName: "Home", routeValues: new { Id = item.id, pagename = item.heading.ToSeoUrl() }, htmlAttributes: null)