开发者

ASP.NET MVC2 : DateTime modelbinding via HTTP GET

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, wi开发者_开发百科th 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 ?


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]);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜