0

我想在url中的單詞之間添加' - '或'+'。例如網址,如:如何在asp.net中編寫url?mvc

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

當前網址的外觀如何? item.heading的內容是什麼?它是如何生成的? –

回答

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) 
+0

我必須在控制器類中添加這個函數,否則在哪裏? – user3041736

+0

你可以在應用程序中創建一個名爲helper的類。 –

+0

如何從我的控制器方法調用Html Helper方法?簡單地使用靜態類HtmlHelper不起作用。 – user3041736