Change date format in ASP.NET MVC application

前端 未结 4 1684
孤街浪徒
孤街浪徒 2020-12-29 08:18

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

4条回答
  •  无人及你
    2020-12-29 09:01

    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 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.

提交回复
热议问题