Reputation: 1621
I am struggling how to properly allow dashes / hypens in a URL in my MVC 4 / ASP.NET 4.5 app...for some reason MVC converts the dashes to underscores which is not what i want.
I've done a good bit of searching around before i posted the question, still can't find any easy solution. Everything i found seems way out of whack for such a simple configuration.
Basically, i would like to be able to access the following URL:
www.mysite.com/dashes-in-url
So for example, i created a controller named:
dashes-in-urlController.cs
The controller was named fine and allowed the dashes in the controller name.
However, when i created a view for the Index for the above controller, it created the view as:
Folder: /Views/dashes_in_url
With an Index.cshtml file in that folder - but it replaced my dashes with underscores.
So i have to access the url as:
www.mysite.com/dashes_in_url
with underscores instead of with the dashes in the URL.
Does anyone know of any elegant, simple solution to achieve what i'm trying to do?
Any help in this matter would be greatly appreciated, thanks!
Upvotes: 4
Views: 2698
Reputation: 900
I've developed an open source NuGet library for this problem which implicitly converts EveryMvc/Url to every-mvc/url.
Dashed urls are much more SEO friendly and easier to read. (More on my blog post)
NuGet Package: https://www.nuget.org/packages/LowercaseDashedRoute/
To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the "Online" tab type "Lowercase Dashed Route", and it should pop up.
Alternatively, you can run this code in the Package Manager Console:
Install-Package LowercaseDashedRoute
After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:
routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
new DashedRouteHandler()
)
);
That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.
Open Source Project Url: https://github.com/AtaS/lowercase-dashed-route
Upvotes: 7