Tag Archives: mvc

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;
}
Tagged
Follow

Get every new post delivered to your Inbox.

Join 58 other followers