Passing DataTime javascript to ASP.NET MVC Controller by Ajax

3

I'm having trouble passing javascript date 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 the 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 property ModelA.DataNascimento = null , in the other properties everything works ..

Does anyone have any idea what might be happening ??

Thank you !!

[Edit]

HTML field code

<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="" />
    
asked by anonymous 31.08.2016 / 20:18

1 answer

2

The way it worked, after much hitting the head 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());
    ....
}

DatetimeBinder class ()

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 do not know if it's the "right" way, but it was the only way it worked for me.

    
01.09.2016 / 13:22