以MM / dd / yyyy格式显示日期

时间:2015-10-04 21:00:29

标签: jquery asp.net-mvc-5.2

我正在使用默认文化为en-GB的MVC 5.2应用程序,其默认ShortDatePattern为dd / MM / yyyy。我想将日期模式更改为MM / dd / yyyy以用于查看/编辑模型。

显示模型时工作正常。但是在编辑模式下显示日期时会遇到问题。以下是我的代码 -
ViewModel

[Display(Name="License Renewal Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString="{0:MM/dd/yyyy}", ApplyFormatInEditMode=true)]
public DateTime LicenseRenewalDate { get; set; }

.cshtml

@Html.EditorFor(model => model.LicenseRenewalDate, new { htmlAttributes = new { @class="form-control" } })
@Html.ValidationMessageFor(model => model.LicenseRenewalDate, "", new { @class="text-danger" })

以下是编辑模式的屏幕截图 - enter image description here

如您所见,默认日期模式在编辑框中显示为dd / MM / yyyy,日期选择器控件不允许我更改它。 如何将日期选择器控件设置为默认日期模式为MM / dd / yyyy?

仅供参考,我正在使用

jQuery.Validation version - 1.11.1 and 
Microsoft.jQuery.Unobtrusive.Validation version - 3.2.3

谢谢!

1 个答案:

答案 0 :(得分:1)

在Web.Config中定义默认文化

<globalization uiCulture="es" culture="es-en" />

OR

我们可以使其他数据类型(如DateTime)获得自己的自定义编辑器,只需将部分View放在Sharedfolder下的EditorTemplates文件夹中,并在目标数据类型之后命名。您需要自己创建此文件夹,因为它不会自动添加到项目中。

DateTime.cshtml可能看起来像这样......

@model  DateTime?

@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : 

string.Empty),new { @class = "datePicker" , 

@readonly = "readonly"})

以及像这样的jQuery代码片段,将jQuery UI日期选择器与类datePicker关联

<script>

     $(function () {

         $(".datePicker").datepicker({

            showOn: "button",

             buttonImage:  "/images/calendar-icon.png",

             buttonImageOnly: true,

            buttonText: "Select date"

         });

     });

</script>