I\'m posting an object to an MVC controller. The object contains a field called StartDt and on the client it is a javascript Date object in local time.
When I call J
I found a gist on Google with code for an ISO 8601 compliant DateTime Model Binder, and then modified it like this:
public class DateTimeBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var name = bindingContext.ModelName;
var value = bindingContext.ValueProvider.GetValue(name);
if (value == null)
return null;
DateTime date;
if (DateTime.TryParse(value.AttemptedValue, null, DateTimeStyles.RoundtripKind, out date))
return date;
else
return base.BindModel(controllerContext, bindingContext);
}
}
I believe the gist code is too restrictive - it wants 6 decimal places on seconds or it will not accept the timestamp. This uses TryParse instead of TryParseExact, so it will technically accept a LOT of timestamp types. The important part is that it uses the DateTimeStyles.RoundtripKind to respect the time zone implied by the Z. So this is no longer technically an ISO 8601 specific implementation.
You could then hook this into the MVC pipeline with a model binder attribute or with this snippet in an App_Start:
var dateTimeBinder = new DateTimeBinder();
ModelBinders.Binders.Add(typeof(DateTime), dateTimeBinder);
ModelBinders.Binders.Add(typeof(DateTime?), dateTimeBinder);