0

I'm having a problem when submitting the date to a controller.

The Date is sent in JSON Date format (ex: /Date(1456592400000)/). Then using Knockout custom binding and momentjs, the date is converted into the 'DD/MM/YYYY' format.

The datepicker is showing the date correctly as '28/02/2016', but when I send it back to the Controller the date value is '01/01/0001 0:00:00' which caused the model to be invalid.

Before submitted, I checked the console and the date is "2016-02-27T17:00:00.000Z". But if I don't use Knockout custom binding and just use the value binding, it works.

I try to modify the model binder to format the date, as described in this post, but it still doesn't work.

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

        return value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
    }
}

I've set the culture id-ID in the web.config

<globalization uiCulture="id-ID" culture="id-ID" />

How do I solve this problem? Here is the jsfiddle to describe the problem.

Community
  • 1
  • 1
Willy
  • 1,689
  • 7
  • 36
  • 79
  • you need time as well at controller end ? way 1) if you need date part just do `split('T')` and send date part . way 2) in controller make it as string later do a conditional toDateTime conversion . cheers – super cool Mar 04 '16 at 12:52

1 Answers1

0

The time that you see in the console and the one that is sent to server (2016-02-27T17:00:00.000Z) is a ISO 8601 representation of the selected date converted to UTC.

So in the model binder you need to treat it accordingly:

public class DateTimeBinder : IModelBinder
{
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    if(value == null)
    {
       return base.BindModel(controllerContext, bindingContext);
    }

    DateTime date;
    if (DateTime.TryParse(value.AttemptedValue, null, DateTimeStyles.RoundtripKind, out date))
    {
       return date.ToLocalTime(); //will convert the dateTime to your local time
    }

    return base.BindModel(controllerContext, bindingContext);

}
Alex Art.
  • 8,711
  • 3
  • 29
  • 47