2013-03-22 61 views
1

我想我的MVC的URL像這樣:爲什麼ActionLink URLEncode不?

http://www.site.com/project/id/projectname 

例子:

http://www.site.com/project/5/new-website 

我的控制器:

public ActionResult Details(int id, string projectname) 

任何我的ActionLink的是:

@Html.ActionLink("click here", "Details", "Project", new { id = project.ProjectID, projectname = project.ProjectName }) 

和我的路線是:

routes.MapRoute(
    "Project", 
    "project/{id}/{projectname}", 
    new { controller = "Project", action = "Details", id = "", projectname = "" } 
    ); 

當然該系統具有足夠的信息還有,要知道項目名稱將是URL的一部分,所以應該進行urlencode的鏈接,並因此與連字符替換空格?但它沒有,所以空格變成%20我不知道我在哪裏定製這個?我是否重寫了Html.ActionLink?在每次編輯時在數據庫中存儲名稱的「URL-ready」版本 - 看起來像是一種浪費,應該在飛行中自動完成。我不想在每次使用Html.ActionLink時都要調用「FriendlyURL」函數 - 同樣,它應該自動處理。

+2

你可能想slugify您的項目名稱。 http://stackoverflow.com/questions/2920744/url-slugify-alrogithm-in-c – RK911 2013-03-22 20:31:49

回答

1

更改空格字符%20 URL編碼的結果。當您對空格字符進行URL編碼時,它不會被轉換爲連字符。如果確實如此,那麼當URL編碼時,你認爲連字符會轉換爲什麼?

正如@ RK911指出的,你想要做的是創建一個slug

有幾個方法可以做到這一點:

1)限制你的projectname數據爲不允許空間,並且只允許連字符(數據錄入過程中使用可能驗證就可以了)。

2)將slug分別存儲在數據庫中,如projectslug

3.)創建一個擴展方法,它將爲您「即時」執行此操作。

下面是使用the link that @RK911 referenced的#3的例子:

public static class SlugExtensions 
{ 
    public static string AsSlug(this string phrase) 
    { 
     string str = phrase.RemoveAccent().ToLower(); 
     // invalid chars   
     str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); 
     // convert multiple spaces into one space 
     str = Regex.Replace(str, @"\s+", " ").Trim(); 
     // cut and trim 
     str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); 
     str = Regex.Replace(str, @"\s", "-"); // hyphens 
     return str; 
    } 

    private static string RemoveAccent(this string txt) 
    { 
     byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt); 
     return System.Text.Encoding.ASCII.GetString(bytes); 
    } 
} 

@Html.ActionLink("click here", "Details", "Project", 
    new { id = project.ProjectID, 
    projectname = project.ProjectName.AsSlug() }) 
相關問題