Pass DataTime javascript to ASP.NET MVC Controller by Ajax

Question:

I have a problem to pass the javascript data to the Controller via ajax…

Model:

public class ModelA{
   ....
   [Required]
   DataType(DataType.Date)]
   DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
   Display(Name = "Data de Nascimento")]
   public DateTime? DataNascimento { get; set; }
   ....
}

In the html field is 'type=date'

And JavaScript with all the attempts I've made so far…

var postForm = {
            ...
            'DataNascimento' : $('#DataNascimento').val() //original
            //'DataNascimento': '2011-04-02 17:15:45',    //tentativa
            //'DataNascimento': new Date().toISOString()  //tentativa
            //'DataNascimento': '02-04-2011'              //tentativa
            //'DataNascimento': '02/04/2011'              //tentativa
            ...
        };

        $.ajax({
            url: "/Portal/Register",
            type: "post",
            data: postForm,
            success: function (response) {
                alert("Dados enviados...");
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("Erro");
                console.log(textStatus, errorThrown);
            }
        });

In all cases, the controller receives the ModelA.DataNascimento = null property, in the other properties everything works..

Does anyone have any idea what might be going on??

Thanks!!

[Edit]

HTML code of the field

<input class="form-control text-box single-line" data-val="true" data-val-required="O campo Data de Nascimento é obrigatório." id="DataNascimento" name="DataNascimento" type="date" value="" />

Answer:

The way it worked, after a lot of head banging, was as follows:

Create custom Binders for DateTime (C#)

Global.asax 

protected void Application_Start()
{
    ....
    ModelBinders.Binders.Add(typeof(DateTime), new DatetimeBinder());
    ModelBinders.Binders.Add(typeof(DateTime?), new DatetimeBinder());
    ....
}

Classe DatetimeBinder()

public class DatetimeBinder : IModelBinder
{

    public DatetimeBinder() { }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?))
        {
            String data = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
            DateTime dt = new DateTime();
            bool okData= DateTime.TryParse(data, CultureInfo.GetCultureInfo("pt-BR"), DateTimeStyles.None, out dt);
            if (okData)
            {
                return dt;
            }
            else
            {
                if (Nullable.GetUnderlyingType(bindingContext.ModelType) != null)
                    return null;

                return new DateTime();
            }
        }
        else
        {
            return null;
        }

    }
}

I don't know if it's the "right" way, but it was the only way it worked for me

Scroll to Top