0

Using a jQuery DatePicker function in my C# MVC program but its giving me an error either saying "Invalid Date" or my default date of today "17/05/2017" is invalid.

Here's my jQuery as well as my Labels/Editors in my Create.cshtml:

<div class="editor-label">
        @Html.LabelFor(model => model.DateOfReading)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.DateOfReading)
        @Html.ValidationMessageFor(model => model.DateOfReading)
    </div>

 <script>
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
    jQuery(function ($) { //on document.ready


        $('#DateOfReading').datepicker({ dateFormat: 'dd/mm/yy', maxDate: 0, defaultDate: 0 }).val(new Date().toLocaleDateString());
    })
}
</script>

Here's my entity:

 [Required(ErrorMessage = "You must input a date")]
    [Display(Name = "Date of Meter Reading")]
    [DataType(DataType.Date)]
    public DateTime DateOfReading { get; set; }
KOD459
  • 77
  • 1
  • 11

1 Answers1

2

Add this attribute to your method.

[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
tmutton
  • 1,091
  • 7
  • 19
  • 42
  • I get the message "The value '‎17‎/‎05‎/‎2017' is not valid for Date of Meter Reading." still with that – KOD459 May 17 '17 at 14:28
  • I think [Display(Name = "Date of Meter Reading")] should be [Display(Name = "DateOfReading")] as well. – tmutton May 17 '17 at 14:36
  • What value is the jquery plugin giving? Put a console.log in there if you can. – tmutton May 17 '17 at 15:04
  • Hey, I'm very new to jQuery but where should I put the console.log? – KOD459 May 17 '17 at 15:15
  • Can you provide a little more information? At what point is the error occuring? When you select a date or when you submit the form to the backend (mvc)? – tmutton May 17 '17 at 17:19
  • Happens when I try to submit the form – KOD459 May 18 '17 at 08:08
  • Hey tmutton, I'm fairly sure it has something to do with the toLocaleDateString! – KOD459 May 18 '17 at 09:05
  • 1
    Yes I saw the duplicate post answer. Think you might have better luck following that route. Sorry I couldn't solve this for you. – tmutton May 18 '17 at 14:03