3

I have a field declared in my model:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? dataCreazione { get; set; }

in the view i render the field with helper:

@Html.EditorFor(m => m.dataCreazione )

And when i submit the form with dataCreazione null (via js - form serialize), with the debug i see the dataCreazione field value null (correct) in controller method, but ModelState is invalid with message ("dataCreazione should be formated .....").

Why validation on nullable DateTime? How i can avoid it? I wanna be able to submit DateTime null without make modelstate invalid.

Edit: I submit form via js with:

$.post(this.form.attr('action'), this.form.serialize(), function (data) {
    if (data.url == null) {
        _this.modal.find('.modal-content').empty();
        _this.modal.find('.modal-content').html(data);
        _this.bindEvents();
    } else {
        window.location.href = data.url;
    }
});

If i print form.serialize() i see parameter will be send dataCreazione=. In another point of application i submit a form with date null via Http GET and on server side the datetime is initialized with 01/01/0001 (and modelstate valid).

I just not complain why i can't submit a datetime null and receive a modelstate invalid.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Diego
  • 31
  • 4
  • Can you explain me why? Documentation say that datatype annotation is only for display and not influence validation model – Diego Dec 04 '18 at 21:24
  • I just tried your code but fail to reproduce your issue. 1. How do you submit the form? could you please post the complete payload sent to the server ? 2. Also, it's better to show us the action method on server side. – itminus Dec 05 '18 at 01:34
  • Integrated question – Diego Dec 05 '18 at 06:34
  • Still cannot reproduce . Could you please post your server side code and the payload sent to the server? – itminus Dec 05 '18 at 08:03
  • I found error, there is a custom model binder that validate datetime always. Can be closed, thanks. – Diego Dec 06 '18 at 09:44

1 Answers1

0

I just ran into this issue now on .net Core 2.2 (My project might have been actually created in 2.1 last year around the time this question was asked).

The solution for me was changing the selectlist option I created outside the tag helper (with no value):

<option>Please select one</option>

To be:

<option value="">Please select one</option>

It wasn't obvious either as the null value was being passed back to the controller which should be valid. It was only apparent in the form error:

The value "Please select one" is not valid for...

Now when debugging, the model passed back to the controller looks the same (according to VS2017), but ModelState.IsValid evaluates to true and everything works as expected.

Sum None
  • 2,164
  • 3
  • 27
  • 32