ASP.NET MVC Routing: Clean Urls - from camel case to hyphenated words
Asked Answered
M

1

1

I currently have an action defined in my controller:

    // GET: /schools/:cleanUrlName/data-loggers
    public ActionResult DataLoggers(string cleanUrlName)
    {
        return View();
    }

This works when I hit "/schools/brisbane-state-high-school/dataloggers", however - as per the comment - I want to access it via a slightly cleaner url (using hyphens): "/schools/brisbane-state-high-school/data-loggers". I know I could write a route to accomplish this, but I was hoping I wouldn't have to write a new route for every multi-worded action/controller. Is there a better way to address this?

Misanthrope answered 3/9, 2013 at 5:11 Comment(0)
V
4

You can use the ActionNameAttribute to create an alias for your action name.

So you just need to annotate your multi worded actions:

[ActionName("data-loggers")]
public ActionResult DataLoggers(string cleanUrlName)
{
    return View("DataLoggers");
}

But because this affects also the view discovery therefore you need to return View("DataLoggers") so you are probably better with creating custom routes for your multi worded actions.

Veradis answered 3/9, 2013 at 5:24 Comment(3)
If you want some more generic solution, you can have a look on the IIS url rewriting feature or you can derive from Route and remove the hyphens for the action name with overriding the GetRouteData method...Veradis
Excellent! I think I'll use ActionName since it is just one line compared to the several lines required per route. I feel the RouteConfig would get quite large if I I wrote a route for each multi-word action. Thanks.Misanthrope
i am no longer able to add view with dash as said here , when tried this appears: The name is not allowed to contain any of these characters: . - @ <, . so i guess only solution is to rename the view after addingHypercatalectic

© 2022 - 2024 — McMap. All rights reserved.