asp.net-mvcasp.net-mvc-3asp.net-mvc-4razormvc-editor-templates

Change date format in ASP.NET MVC application


I need to change date format to be dd.MM.yyyy. I am getting client side validation error because ASP.NET MVC date format is different from what I expect on the server.

In order to change ASP.NET MVC date format I tried:

Web.config:

<globalization uiCulture="ru-RU" culture="ru-RU" />

Model:

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

Editor template:

@model DateTime?
@Html.TextBox(string.Empty, (Model.HasValue 
    ? Model.Value.ToString("dd.MM.yyyy")
    : string.Empty), new { @class = "date" })

View:

@Html.EditorFor(m => m.ServiceCreatedFrom, new { @class = "date" })

Even Global.asax:

public MvcApplication()
{
    BeginRequest += (sender, args) =>
        {
            var culture = new System.Globalization.CultureInfo("ru");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        };
}

Nothing worked for me.


Solution

  • The following should work:

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

    and in your editor template:

    @model DateTime?
    @Html.TextBox(
        string.Empty, 
        ViewData.TemplateInfo.FormattedModelValue, 
        new { @class = "date" }
    )
    

    and then:

    @Html.EditorFor(x => x.ServiceCreatedFrom)
    

    The second argument you were passing to the EditorFor call doesn't do what you think it does.

    For this custom editor template, since you specified the format explicitly on your view model property the <globalization> element in your web.config and the current thread culture will have 0 effect. The current thread culture is used with the standard templates and when you didn't override the format with the [DisplayFormat] attribute.