tags:

views:

29

answers:

2

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!

+1  A: 
    public VoiceController()
    {
        var locale = this.RouteData.Values["locale"];
    }
Craig Stuntz
I would have thought that would work as well, but unfortunately not. I get: Object reference not set to an instance of an object.If I move that same line of code down to the index action block, it works just fine.
Dave
Sorry, I didn't notice that you were in the constructor. You can't read *anything* from `this` in the constructor. As you say, it works fine in the action.
Craig Stuntz
+2  A: 

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

jim
you rock. thanks!although I have no clue what System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName is :-)
Dave
Dave, that was purely my 'fallback' in the case of locale being null i.e. if the route is null... cheers
jim