2

Hello I am currently having a real pain accepting dates across all 4 browsers, Internet Explorer, Chrome, Edge and Safari in MVC 5.

I am using Jquery-ui Date Picker.

With my current code and set up outlined below I can accept dates within Internet Explorer and Chrome, Edge and Safari return "The field Date of Purchase: must be a date."

I am pretty basic in my skills, but over the past year I have learnt a considerable amount, but to be honest I am more frustrated with how a simple thing like a Data field can be such a pain, searching has just run me around in circles, I have working code but not across all browsers.

If somebody could please point me in the right direction to a similar question (I can not find one after a full day looking), or to a solution to cover all bases or just help shine a torch on my dimness it would be greatly appreciated.

My Field is declared in its model like this.

    [Required]
    [Display(Name = "Date of Purchase:")]
    [DisplayFormat(DataFormatString = "{0:yyyy/MMM/dd}",
    ApplyFormatInEditMode = true)]
    public System.DateTime date_of_purchase { get; set; }

My web.config declares the globalization as follows :

<globalization culture="auto" uiCulture="auto" />

On my HTML Razor Page I call Jquery Datepicker as below:

<script>
$(document).ready(function () {
    $("#@Html.IdFor(m => m.date_of_purchase)").datepicker({dateFormat: 'yy/MM/dd',  maxDate: "0" });
});
</script>

The Form Field for the Date entry is below:

<div class="form-group">
    @Html.LabelFor(model => model.date_of_purchase, htmlAttributes: new { @class = "control-label col-md-4" })
        <div class="col-md-8">
            @Html.EditorFor(model => model.date_of_purchase, new { htmlAttributes = new { @class = "form-control", @readonly = "true", @placeholder = "Required" } })
            @Html.ValidationMessageFor(model => model.date_of_purchase, "", new { @class = "text-danger" })
        </div>
</div>

My Controller is below but this is nothing I believe to do with the problem bog standard.

    public async Task<ActionResult> VehicleRegistration([Bind(Include = "User_Email,Serial_No,IMEI_No,dealer_id,dealer_name,date_of_purchase")] VehicleRegistration vehicleReg)
    {
        if (ModelState.IsValid)
        {
            IQueryable<Dealer> dealerSort;
            dealerSort = db.Dealers.Where(o => o.Name == vehicleReg.dealer_name);
            vehicleReg.dealer_id = dealerSort.Single().DealerID;
            IQueryable<AspNetUser> UserSort;
            UserSort = db.AspNetUsers.Where(o => o.Email == vehicleReg.User_Email);
            string userSortResult = UserSort.Single().Id;
            string userTitle = UserSort.Single().Title;
            string userSurname = UserSort.Single().Surname;
            string userTel = UserSort.Single().Home_Phone;
            string userMob = UserSort.Single().Mobile_Phone;

            string callbackUrl = await SendEmailVehicleRegistrationRequest(userSortResult, "Vehicle Registration Request", vehicleReg.User_Email, vehicleReg.Serial_No, vehicleReg.IMEI_No, vehicleReg.dealer_id, vehicleReg.dealer_name, vehicleReg.date_of_purchase, userTitle, userSurname, userTel, userMob);

            ViewBag.Message = "An email has been sent to " + vehicleReg.dealer_name + ", requesting them to complete the sale of your vehicle." +
            " A copy has also been sent to Swift Command Support, if you do not receive confirmation within 3 days please contact Swift Command Support.";
            return View("Info");
        }

        return View(vehicleReg);
    }
Andy Donegan
  • 782
  • 1
  • 9
  • 30
  • Why is the field `readonly`? – ManojAnavatti Apr 04 '16 at 10:47
  • @ManojAnavatti It is read only as the Jquery Date Picker pops up when the user clicks upon it. I wanted to stop users having the ability to enter strange date formats and allow the Date Picker to control the situation. – Andy Donegan Apr 04 '16 at 10:57
  • Sound like you are getting a client side validation error. By default `jquery.validate.js` will validate dates based on `MM/dd/yyyy` format (or ISO format `yyyy-MM-dd`) so to solve the client side issue you need to reconfigure the validator (refer [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) for an example) and change the format to `dateFormat: 'yy-mm-dd'` (lower case m) and in the attribute, use `DataFormatString = "{0:yyyy-MM-dd}"` –  Apr 04 '16 at 12:02
  • @StephenMuecke Hi Stephen, you spotted it exactly. Thank you very much I have amended all of my code and my other sites too. – Andy Donegan Apr 04 '16 at 17:08
  • @StephenMuecke Unfortunately I can not accept my own answer for two days, if you would like to post your comment as the Answer Stephen I will gladly Mark it correctly. – Andy Donegan Apr 04 '16 at 17:13
  • No need, you have added the answer :) –  Apr 04 '16 at 22:34

1 Answers1

2

This Solution is thanks to @StephenMuecke who spotted my problem.

if my Model I amended it and changed the Month from MMM to MM new code below.

[Required]
[Display(Name = "Date of Purchase:")]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public System.DateTime date_of_purchase { get; set; }

On the page the set up for Jquery Date Picker I changed the date format to 'dd/mm/yy' which is what I always wanted but could not get to work across two browsers never mind all 5. It was previously 'yy/MM/dd'.

<script>
    $(document).ready(function () {
    $("#@Html.IdFor(m => m.date_of_purchase)").datepicker({ dateFormat: 'dd/mm/yy',  maxDate: "0" });
});
</script>

Thanks to everyones input I know have it working in the date format I require across IE, Edge, Chrome, FireFox and Safari.

Andy Donegan
  • 782
  • 1
  • 9
  • 30