Brett
Brett

Reputation: 2746

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

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?

Upvotes: 1

Views: 1220

Answers (1)

nemesv
nemesv

Reputation: 139748

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.

Upvotes: 4

Related Questions