TheEdge
TheEdge

Reputation: 9851

MVC Date Culture Issue

I am using ASP.NET MVC 5 with ASP.NET 4.51. I am trying to validate my dates as dd/MM/yyyy eg. 31/01/1960 but model validation keeps on telling me that it is an invalid date.

Following suggestions from other SO posts:

I have the following in my web.config:

<system.web>
    <globalization uiCulture="en" culture="en-AU" />
</system.web>

My view model looks like this:

public class PassengerItem
{
    public PassengerItem()
    {
        DateOfBirth = new DateTime(1960, 1, 1);
    }

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

public class BookingProcessViewModel
{
    /// <summary>
    ///     Class constructor
    /// </summary>
    public BookingProcessViewModel()
    {
        ErrorMessages = new List<string>();
        Passengers = new List<PassengerItem>();

        //Populate with 10 passengers. We show/hide these in the view. Currently we only allow a max of 4 pax to be booked at a time
        for (int i = 0; i < 4; i++)
        {
            Passengers.Add(new PassengerItem());
        }
    }

    public List<PassengerItem> Passengers { get; set; }
}

and the controller is being hit with a POST viz:

    [HttpPost]
    public ActionResult Process(BookingProcessViewModel aViewModel)
    {
    }

but I always get the following error in the model state:

enter image description here

The data entry for the date is being done using jQueryUI with the following HTML:

<input aria-invalid="false" class="form-control hasDatepicker valid" 
data-jqui-dpicker-changemonth="True" 
data-jqui-dpicker-changeyear="True" 
data-jqui-dpicker-constraininput="True" 
data-jqui-dpicker-dateformat="dd/mm/yy" 
data-jqui-dpicker-defaultdate="01/01/1901" 
data-jqui-dpicker-maxdate="24/08/2015" 
data-jqui-type="datepicker" id="Passengers_0__DateOfBirth" 
name="Passengers[0].DateOfBirth" value="31/01/1960" type="text">

So client side validation is passing, but server side there is an issue and I just cannot figure it out. This is driving me nuts. Can anyone shed any light?

Upvotes: 0

Views: 2806

Answers (1)

user3559349
user3559349

Reputation:

Change you web.config file to (both must be en-AU)

globalization uiCulture="en-AU" culture="en-AU" />

The DefaultModelBinder is using the value of uiCulture to convert the value to a DateTime (notice in your screenshot that its Culture: {en}

Side note. You have [DataType(DataType.Date)] which will generate the browsers HTML5 datepicker if your using @Html.EditorFor() which means that you need to use DataFormatString = "{0:yyyy-MM-dd}" in order for it to work correctly.

Upvotes: 1

Related Questions