Search code examples
c#asp.net-mvckendo-asp.net-mvcglobalizationkendo-datepicker

Kendo DatePicker Globalization Binding Issue


I have an asp.net MVC application with "es-MX" culture. Here's what I have in my web.config file:

<globalization enableClientBasedCulture="true" uiCulture="es-MX" culture="es-MX"></globalization>

And, here's what I have in my _Layout page:

<script type="text/javascript">
    $(function () {
        //set current to the "es-MX" culture script
        kendo.culture("es-MX");
    })
</script>

I have a Kendo DatePicker like this:

@(Html.Kendo().DatePickerFor(model => model.StartDate)
    .HtmlAttributes(new { @class = "input-field" })
)

When I post back the form to my controller, the StartDate field is null.

Here's the response I get from the server:

"Errors":{"StartDate":{"errors":["The value \u002707/10/2016 12:00:00 a. m.\u0027 is not valid for Fecha de Inicio."]}}

By the way, the Accept-Language of the request that is sent to the server is "en-US", which I find strange.

UPDATE:

I tried to use a custom model binder for DateTime, like this:

public class DateTimeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (string.IsNullOrWhiteSpace(value.AttemptedValue))
            return null;

        DateTime dateTime;
        var isDate = DateTime.TryParse(value.AttemptedValue, Thread.CurrentThread.CurrentUICulture, 
            DateTimeStyles.None, out dateTime);

        if (!isDate)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "La fecha es válido.");
            return DateTime.UtcNow;
        }

        return dateTime;
    }
}

But, it looks like the problem is with the time part of the date passed to the controller. The value 07/10/2016 12:00:00 a. m. is not recognized as a date by neither the "es-MX" nor the "en-US" culture.


Solution

  • I figured what the issue was. According to the documentation, the Kendo UI culture scripts are generated based on the Windows 8 formats. I'm using Windows 7. So, I'll have to put this Culture Helper on top of the page to make sure the scripts are generated based on the current .NET or specified culture:

    @Html.Kendo().Culture()
    

    Without this helper, the dates posted to the server will be like 07/10/2016 12:00:00 a. m. (note the space between a. and m.), and that's my MVC is not able to bind them. After using the helper, the dates will be like 07/10/2016 12:00:00 a.m. (without the space).