28

I'm using ASP.NET MVC 3.
My ViewModel looks like this:

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

In view, I have something like this:

<div class="editor-field">
    @Html.EditorFor(model => model.StartDate)
    <br />
    @Html.ValidationMessageFor(model => model.StartDate)
</div>

StartDate is displayed in correct format, but when I change it's value to 19.11.2011 and submit the form, I get the following error message: "The value '19.11.2011' is not valid for StartDate."

Any help would be greatly appreciated!

šljaker
  • 7,294
  • 14
  • 46
  • 80

3 Answers3

43

You need to set the proper culture in the globalization element of your web.config file for which dd.MM.yyyy is a valid datetime format:

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

For example that's the default format in german: de-DE.


UPDATE:

According to your requirement in the comments section you want to keep en-US culture of the application but still use a different formats for the dates. This could be achieved by writing a custom model binder:

using System.Web.Mvc;
public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName, 
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

which you will register in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
jpaugh
  • 6,634
  • 4
  • 38
  • 90
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • But I wan't use the English culture with different datetime format. Is there any workaround? – šljaker Oct 20 '11 at 12:50
  • @šljaker, yes there is. You will have to write a custom model binder and manually parse the date parameter using the format you like. – Darin Dimitrov Oct 20 '11 at 12:53
  • The globalization Tag is child of the Tag. – encc Dec 11 '13 at 08:29
  • hi, Darin, i have a question,`dd/MM/yyyy` format works fine in local machine, but our website hosted in another country, it needs `MM/dd/yyyy` format else it shows validation error `The field BeginDate must be a date.`, how can i make sever to accept `dd/MM/yyyy` format, will globalization work?, can i add globalization in a View page instead of web.config ? – Shaiju T Apr 02 '15 at 06:08
  • Can I turn off date validation completely? – Akbari Aug 03 '15 at 06:03
  • can change at the iis .net globalization setting. change the culture to your corresponding . – kyorilys Jan 20 '17 at 07:36
  • Is it possible to do this for just a single DateTime field? I have one which needs to be formatted specially, while all others should be formatted as usual. – jpaugh May 23 '17 at 22:27
11

Based upon your comment I see all you want is an english current but with a different date format (Correct me if I'm wrong).

The fact is the DefaultModelBinder uses the culture settings of the server for form data. So I can say the server use "en-US" culture but with a different date format.

You can do something like this in the Application_BeginRequest and you are done!

protected void Application_BeginRequest()
{
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;
}

Web.Config

<globalization culture="en-US" />
VJAI
  • 32,167
  • 23
  • 102
  • 164
0

Added this below code to global.asax.cs file

protected void Application_BeginRequest()  
{        
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());     
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = info;     
}

And added the below to web.config under <system.web>

<globalization culture="en-US">;
Yirkha
  • 12,737
  • 5
  • 38
  • 53
Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45