Pass Datatime javascript to ASP.NET MVC Controller by Ajax

Asked

Viewed 455 times

3

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

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

Thank you!!

[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="" />
  • Can you display the html for this field ? In order to analyze what is happening, apparently this field has no id so it is returning null

  • Hi, thanks @Kirmayrtomaz for the return, has id yes, including if playing on the console $('#DataNascimento').val() it shows the output example: "1992-02-01"

  • I tested here, if you give Ubmit in the form the date goes with the right value.. but I need to do via ajax..

  • Guy looking at this piece of code js is right, I don’t know what it is =/

  • I did everything I could, here in the pt stack and in the stack.. I upgraded to the kk query.. I don’t know what else to do heheh, but thanks for the help @Kirmayrtomaz

1 answer

2


The way it worked, after a lot of head bashing was the following:

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 don’t know if it’s the "right" way, but it was the only way it worked for me

Browser other questions tagged

You are not signed in. Login or sign up in order to post.