ASP.Net MVC localizable GET parameters

I’ve now written a solution to my date localization problem in MVC 1.0.  It looks like MVC 2.0 will require a different implementation because they’ve changed that logic.  It looks like it’s mostly for the better.

Essentially I’ve added a hidden value with the name ‘hl’ onto my GET forms with the System.Globalization.CultureInfo.CurrentCulture.LCID so that I know which culture to use when parsing the values.

I’ve then created my own version of the ValueProviderDictionary and within our own Controller base class we set that after the Initialize is called.  That ValueProviderDictionary is identical except that before the query parameters are processed I see if there is a the culture value on the query and read that and use it instead of the Invariant culture if possible.

I’m only doing the query parameters at the moment since I’m not sure if it’s a good idea to the route values.


    NameValueCollection queryString = ControllerContext.HttpContext.Request.QueryString;
    if (queryString != null) 
    {
        CultureInfo getCulture = ReadCulture(invariantCulture, queryString);
        string[] keys = queryString.AllKeys;
        foreach (string key in keys) {
            string[] rawValue = queryString.GetValues(key);
            string attemptedValue = queryString[key];
            ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, getCulture);
            AddToDictionaryIfNotPresent(key, result);
        }
    }

private static CultureInfo ReadCulture(CultureInfo invariantCulture, NameValueCollection queryString)
{
    CultureInfo getCulture = invariantCulture;
    if (!String.IsNullOrEmpty(queryString["hl"]))
    {
        string host_language = queryString["hl"]; // host language
        try
        {
            int language;
            if (Int32.TryParse(host_language, out language))
                getCulture = CultureInfo.GetCultureInfo(language);
        }
        catch (Exception)
        {
            Errors.Log.WarnFormat("Encountered unexpected culture {0}", host_language);
        }
    }
    return getCulture;
}
Advertisements

One thought on “ASP.Net MVC localizable GET parameters

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s