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 ?

1 Answer 1

1

This seems to be by design :

http://www.pagedesigners.co.nz/2009/12/asp-net-mvc-datetime-binding-and-culture-unaware-urls/

And the solution (from: CultureInfo issue with Modelbinding double in asp.net-mvc(2)) 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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.