asp.net-mvc MVC4 DataType.Date EditorFor 不会在 Chrome 中显示日期值,在 Internet Explorer 中很好
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12633471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer
提问by Ben Finkel
I'm using the DataType.Date attribute on my model and an EditorFor in my view. This is working fine in Internet Explorer 8and Internet Explorer 9, but in Google Chromeit is showing a date picker and instead of displaying the value it just displays "Month/Day/Year" in faded gray text.
我在我的模型上使用 DataType.Date 属性,在我的视图中使用一个 EditorFor。这在Internet Explorer 8和Internet Explorer 9 中工作正常,但在Google Chrome 中它显示一个日期选择器,而不是显示值,它只以淡灰色文本显示“月/日/年”。
Why won't Google Chrome display the value?
为什么 Google Chrome 不显示该值?
Model:
模型:
[DataType(DataType.Date)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
View:
看法:
<td class="fieldLabel">Est. Pur. Date</td>
<td class="field">@Html.EditorFor(m=>m.EstPurchaseDate)</td>




回答by Darin Dimitrov
When you decorate a model property with [DataType(DataType.Date)]the default template in ASP.NET MVC 4 generates an input field of type="date":
当您使用[DataType(DataType.Date)]ASP.NET MVC 4 中的默认模板装饰模型属性时,会生成一个输入字段type="date":
<input class="text-box single-line"
data-val="true"
data-val-date="The field EstPurchaseDate must be a date."
id="EstPurchaseDate"
name="EstPurchaseDate"
type="date" value="9/28/2012" />
Browsers that support HTML5 such Google Chrome render this input field with a date picker.
支持 HTML5 的浏览器(例如 Google Chrome)使用日期选择器呈现此输入字段。
In order to correctly display the date, the value must be formatted as 2012-09-28. Quote from the specification:
为了正确显示日期,该值必须格式化为2012-09-28. 引用规范:
value:A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.
值:[RFC 3339] 中定义的有效完整日期,附加条件是年份部分是四位或更多位数字,表示大于 0 的数字。
You could enforce this format using the DisplayFormatattribute:
您可以使用以下DisplayFormat属性强制执行此格式:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
回答by Charlie
In MVC5.2, add Date.cshtml to folder ~/Views/Shared/EditorTemplates:
在 MVC5.2 中,将 Date.cshtml 添加到文件夹 ~/Views/Shared/EditorTemplates:
@model DateTime?
@{
IDictionary<string, object> htmlAttributes;
object objAttributes;
if (ViewData.TryGetValue("htmlAttributes", out objAttributes))
{
htmlAttributes = objAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(objAttributes);
}
else
{
htmlAttributes = new RouteValueDictionary();
}
htmlAttributes.Add("type", "date");
String format = (Request.UserAgent != null && Request.UserAgent.Contains("Chrome")) ? "{0:yyyy-MM-dd}" : "{0:d}";
@Html.TextBox("", Model, format, htmlAttributes)
}
回答by Arjan
As an addition to Darin Dimitrov's answer:
作为 Darin Dimitrov 回答的补充:
If you only want this particular line to use a certain (different from standard) format, you can use in MVC5:
如果您只希望此特定行使用某种(不同于标准)格式,则可以在 MVC5 中使用:
@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })
回答by Azoro
In MVC 3 I had to add:
在 MVC 3 中,我必须添加:
using System.ComponentModel.DataAnnotations;
among usings when adding properties:
添加属性时的用途:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Especially if you are adding these properties in .edmx file like me. I found that by default .edmx files don't have this using so adding only propeties is not enough.
特别是如果您像我一样在 .edmx 文件中添加这些属性。我发现默认情况下 .edmx 文件没有使用这个,所以只添加属性是不够的。
回答by bernieb
If you remove [DataType(DataType.Date)]from your model, the input field in Chrome is rendered as type="datetime"and won't show the datepicker either.
如果您[DataType(DataType.Date)]从模型中删除,Chrome 中的输入字段type="datetime"将呈现为并且也不会显示日期选择器。
回答by markpcasey
I still had an issue with it passing the format yyyy-MM-dd, but I got around it by changing the Date.cshtml:
我仍然遇到了它传递格式 yyyy-MM-dd 的问题,但我通过更改 Date.cshtml 解决了这个问题:
@model DateTime?
@{
string date = string.Empty;
if (Model != null)
{
date = string.Format("{0}-{1}-{2}", Model.Value.Year, Model.Value.Month, Model.Value.Day);
}
@Html.TextBox(string.Empty, date, new { @class = "datefield", type = "date" })
}
回答by Blerton Hoxha
Reply to MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in IE
回复MVC4 DataType.Date EditorFor 在 Chrome 中不会显示日期值,在 IE 中没问题
In the Model you need to have following type of declaration:
在模型中,您需要具有以下类型的声明:
[DataType(DataType.Date)]
public DateTime? DateXYZ { get; set; }
OR
或者
[DataType(DataType.Date)]
public Nullable<System.DateTime> DateXYZ { get; set; }
You don't need to use following attribute:
您不需要使用以下属性:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
At the Date.cshtml use this template:
在 Date.cshtml 使用这个模板:
@model Nullable<DateTime>
@using System.Globalization;
@{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
if (Request.Browser.Type.ToUpper().Contains("IE") || Request.Browser.Type.Contains("InternetExplorer"))
{
@Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
}
else
{
//Tested in chrome
DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat;
dtfi.DateSeparator = "-";
dtfi.ShortDatePattern = @"yyyy/MM/dd";
@Html.TextBox("", String.Format("{0:d}", dt.ToString("d", dtfi)), new { @class = "datefield", type = "date" })
}
}
Have fun! Regards, Blerton
玩得开心!问候, 布莱顿
回答by Martin Staufcik
If you need to have control over the format of the date (in other words not just the yyyy-mm-dd format is acceptable), another solution could be adding a helper property that is of type string and add a date validator to that property, and bind to this property on UI.
如果您需要控制日期的格式(换句话说,不仅仅是 yyyy-mm-dd 格式是可以接受的),另一种解决方案可能是添加一个字符串类型的辅助属性,并向该属性添加一个日期验证器,并绑定到 UI 上的此属性。
[Display(Name = "Due date")]
[Required]
[AllowHtml]
[DateValidation]
public string DueDateString { get; set; }
public DateTime? DueDate
{
get
{
return string.IsNullOrEmpty(DueDateString) ? (DateTime?)null : DateTime.Parse(DueDateString);
}
set
{
DueDateString = value == null ? null : value.Value.ToString("d");
}
}
And here is a date validator:
这是一个日期验证器:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DateValidationAttribute : ValidationAttribute
{
public DateValidationAttribute()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
DateTime date;
if (value is string)
{
if (!DateTime.TryParse((string)value, out date))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
else
date = (DateTime)value;
if (date < new DateTime(1900, 1, 1) || date > new DateTime(3000, 12, 31))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
return null;
}
}

