一種方法是在你的字符串以下
string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string thenreplaces spaces with hyphens
cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
現在你可以通過cleanString
(標題,名稱等)到ActoinLink/Url.Action參數,它會工作得很好。
模式從http://snipplr.com/view/18414/string-to-clean-url-generator/
採取我不是100%的正則表達式,如果一些正則表達式英雄可以附和,並提供一個更好的將是巨大的。從測試的正則表達式,它不匹配的空間,但由於第一線替換所有空間用連字符這不應該是一個問題。
更新:
若要使用此代碼,你需要設置你的路由接受額外的參數。
我們將使用一個博客文章標題作爲一個例子。
routes.MapRoute(
"", // Route name
"View/{ID}/{Title}", // URL with parameters
new { controller = "Articles", action = "View"} // Parameter defaults
);
在你的ASP.NET MVC的意見,然後你可以做到以下幾點:
<%= Html.ActionLink("View Article", "View", "Articles", new { ID = article.ID, Title = Html.SanitizeTitle(article.Title) }, null) %>
在前面的例子中,我使用SanitizeTitle
爲HTML helper。
public static SanitizeTitle(this HtmlHelper html, string str)
{
string cleanString = originalString.ToLower().Replace(" ", "-"); // ToLower() on the string thenreplaces spaces with hyphens
cleanString = Regex.Replace(cleanString, @"[^a-zA-Z0-9\/_|+ -]", ""); // removes all non-alphanumerics/underscore/hyphens
return cleanString;
}
我不是正則表達式替換英雄的所有非單詞字符但我認爲這會更好: input = Regex.Replace(input,@「[| \\ /]」,「 - 」); //用「 - 」代替「打破」字符 input = Regex.Replace(input,@「[^ a-zA-Z0-9 -_。〜]」,「」); //替換剩餘的非安全(RFC3986)字符與「」 input = input.Trim(new [] {' - ','_','。','〜'})。ToLower(); //修剪前導或尾隨非字母數字字符並轉換爲小寫 – JohannesH 2010-02-01 06:27:00
廢話...註釋中沒有換行符。 – JohannesH 2010-02-01 06:28:51