Dave
Dave

Reputation: 55

asp.net mvc: read route param inside controller

I'm trying to read the a parameter that I've defined in a route from inside the controller.

The route:

routes.MapRoute(
"BusinessVoice", // Route name
"business/{controller}/{action}/{id}", // URL with parameters
new { controller = "Voice", action = "Index",
id = UrlParameter.Optional, locale = "business" } // Parameter defaults
);

From inside the controller I'd like to be able to read the route parameter locale, but have not idea where to look for it.

The controller:

namespace www.WebUI.Controllers
{
    public class VoiceController : Controller
    {
        public VoiceController()
        {
            ... want to read the locale param here
        }


        public ViewResult Index(string locale)
        {
            return View();
        }

    }
}

Any help is appreciated!

Upvotes: 1

Views: 3780

Answers (2)

jim tollan
jim tollan

Reputation: 22485

Dave,

This is from my basecontroller but you should be able to do exactly the same from a top level one too:

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        var locale = requestContext.RouteData.Values["locale"].ToString() ?? System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
        base.Initialize(requestContext);
    }

good luck

jim

Upvotes: 3

Craig Stuntz
Craig Stuntz

Reputation: 126547

    public VoiceController()
    {
        var locale = this.RouteData.Values["locale"];
    }

Upvotes: 1

Related Questions