Safe way to pass date parameter for ajax call for MVC action

I have an MVC action that takes one of its parameters a DateTime, and if I pass "07/17/2012", it throws an exception saying that the parameter is null but cannot have a null value, but if I pass it is 01/07/2012parsed how Jan 07 2012.

I pass dates to an ajax call in a format DD/MM/YYYY, should I rely on the format MM/DD/YYYYdespite the culture configured in web.config?

This is a simple method, and there is only this date parameter.

+5
source share
2 answers

You have three safe options for sending a date parameter to Asp.NET-MVC:

  • YYYY/MM/DD ISO .
  • POST GET.

  • Model Binder:

, , IModelBinder

public class DateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);

        return date;    
    }
}

Global.Asax:

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());

, , Mvc Framework .

+7

gdoron . , ( post), ( , ).

+1

All Articles