One way to do this is the following on your string
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
Now you can pass the cleanString
(for titles,names etc) into the ActoinLink/Url.Action parameters and it will work great.
The pattern was taken from http://snipplr.com/view/18414/string-to-clean-url-generator/
I'm not 100% on the Regex pattern, if some Regex hero can chime in and offer a better one that would be great. From testing the Regex, it doesn't match spaces, but this shouldn't be a problem because the first line replaces all spaces with hyphens.
Update:
To use this code, you need to setup your routes to accept extra parameters.
We'll use a blog article title as an example.
routes.MapRoute(
"", // Route name
"View/{ID}/{Title}", // URL with parameters
new { controller = "Articles", action = "View"} // Parameter defaults
);
In your ASP.NET MVC views, you can then do the following:
<%= Html.ActionLink("View Article", "View", "Articles", new { ID = article.ID, Title = Html.SanitizeTitle(article.Title) }, null) %>
In the previous example, I use SanitizeTitle
as an 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;
}