Change date format in ASP.NET MVC application
Asked Answered
S

4

15

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.

Stedt answered 14/6, 2013 at 10:10 Comment(3)
i had a similar problem: #13623881Carlow
ugly, but probably the only way :(Stedt
yes, an ugly way. this should be done by the framework ;-)Carlow
K
15

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.

Kosygin answered 14/6, 2013 at 10:17 Comment(11)
Hehe I knew somebody would be quicker :).Androclinium
Thanks for the answer. But I am still getting validation exception, just because app expects MM.dd.yyyyStedt
Would it be overkill to add a custom model binder for this case? I'm not sure if the default model binder considers the current culture.Androclinium
Wait a minute. You seem to be confusing output format and validation. Those are 2 completely different notions. The DisplayFormat attribute controls how the date is rendered to the view. That's it, nothing more. Validation on the other hand is done on the server, when the form is submitted, by the default model binder. You could write a custom model binder which will use the format of the DisplayFormat attribute to validate the date. I have explained this in the following answer: https://mcmap.net/q/490017/-asp-net-mvc3-datetime-formatKosygin
Yes, the default model binder uses the current culture. But there's one more ting to the picture that you should not forget. If you enabled client side validation (unobtrusive javascript) then the date is parsed on the client, using the client browser culture. So if you are using client side validation you will also have to write a custom rule to parse the date on the client using the specified format instead of using the browser settings.Kosygin
Looks like this is an issue. How can fix it?Stedt
You mean the client side validation is the issue?Kosygin
You will have to write a custom date parsing method for the jquery.validate plugin that you are using: #11756726Kosygin
I'm not sure if this would be an option for you, but if I were having your problem and I wanted to accept a user date input, I'd perhaps consider something like the jQuery datepicker, which is localizable. Correct me if I'm wrong, but such a control typically doesn't need client-side validation. I don't know anything about your app though, so Darin's answer may be the best choice.Androclinium
So, this is an answer. I suggest guys to check out the link here #13623881 by SnoopyStedt
i tried editor template in development sever it worked, but finally on production sever this globalization worked for meMesenchyme
S
2

You can change the current culture in your Global.asax file, for application level For Example,

using System.Globalization;
using System.Threading;

protected void Application_BeginRequest(Object sender, EventArgs e)
{    
  CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
  newCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
  newCulture.DateTimeFormat.DateSeparator = "-";
  Thread.CurrentThread.CurrentCulture = newCulture;
}
Snowonthemountain answered 30/12, 2015 at 14:4 Comment(0)
A
1

As a potential aid for identifying the issue, are you able to: 1. Set a breakpoint at the point where you're trying to format the date 2. Use something like the Immediate Window in Visual Studio to evaluate the value of

Thread.CurrentThread.CurrentCulture.Name

If you do this, does it come back with the "ru-RU" culture?

I'm sure I'm not the only one that would be happy to help you work through debugging this. That said, perhaps somebody quicker than me can see the problem straight away :).

Edit: It looks like you're using Razor, so you should be able to set a breakpoint directly in the view file on the line where you're trying to format the date.

Edit #2:

There may be a cleaner way to do this, but if the form data is being posted in dd.MM.yyyy then you might need a custom model binder, something like:

public class CustomModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
              // custom bind the posted date    
        }
}

...which would then get assigned as a model binder in e.g. ApplicationStart in Global.asax.cs.

Let me know if you think this might help and I can elaborate.

Androclinium answered 14/6, 2013 at 10:16 Comment(1)
The culture is ru-RU. I've checked :)Stedt
M
1

finally this one worked for me to get this dd/mm/yyyy format i used date = string.Format("{0}/{1}/{2}", Model.Value.Day, Model.Value.Month, Model.Value.Year);

first create EditorTemplates folder in Sharedfolder, then create a Datetime editor template in Sharedfolder/EditorTemplates/Datetime.cshtml then follow the above link.

in view

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

hope helps someone.

Mesenchyme answered 30/3, 2015 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.