views:

59

answers:

1

I'm getting some trouble binding a date from QueryString :

I have the following model

public class QueryParms
{
    public DateTime Date { get; set; }
}

And the following controller action :

public ActionResult Search( QueryParms query );

I have a form, with a field where I can type my date. If the form is FormMethod.Post, everything is fine, my date is correctly bound to my model.

If the form is FormMethod.Get, it is not working anymore. The date is left to the default value (01/01/0001)

I think it is a culture issue : When i look into the value provider, the FormValueProvider has a culture property set for my date : {fr-FR}. The QueryStringValueProvider doesn't have the culture property set.

Is there a way to set this property ?

A: 

This seems to be by design :

http://www.pagedesigners.co.nz/archive/2009/12/17/asp.net-mvc-datetime-bindng-and-culture-unaware-urls.aspx

And the solution (from: http://stackoverflow.com/questions/3168652/cultureinfo-issue-with-modelbinding-double-in-asp-net-mvc2) is to write a new model binder :

public class DateTimeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var culture = GetUserCulture(controllerContext);

        string value = bindingContext
            .ValueProvider
            .GetValue(bindingContext.ModelName)
            .ConvertTo(typeof(string)) as string;

        if (string.IsNullOrEmpty(value))
        {
            return null;
        }

        return DateTime.Parse(value, culture.DateTimeFormat);
    }

    public CultureInfo GetUserCulture(ControllerContext context)
    {
        var request = context.HttpContext.Request;
        if (request.UserLanguages == null || request.UserLanguages.Length == 0)
            return CultureInfo.CurrentUICulture;

        return new CultureInfo(request.UserLanguages[0]);
    }
}
mathieu