我正在使用数据类型。模型中的Date属性和视图中的EditorFor。这是工作在Internet Explorer 8和Internet Explorer 9,但在谷歌Chrome浏览器显示日期选择器,而不是显示值,它只是显示“月/日/年”在褪色的灰色文本。

为什么谷歌Chrome浏览器不显示该值?

模型:

[DataType(DataType.Date)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }

观点:

<td class="fieldLabel">Est. Pur. Date</td>
<td class="field">@Html.EditorFor(m=>m.EstPurchaseDate)</td>


当前回答

如果你从你的模型中删除[DataType(DataType. date)], Chrome中的输入字段将呈现为type="datetime",也不会显示datepicker。

其他回答

作为Darin Dimitrov的补充回答:

如果你只想让这一行使用某种(不同于标准的)格式,你可以在MVC5中使用:

@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })

如果你从你的模型中删除[DataType(DataType. date)], Chrome中的输入字段将呈现为type="datetime",也不会显示datepicker。

在MVC5.2中,添加“日期”。到~/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)
}

当你用[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" />

支持HTML5的浏览器(如谷歌Chrome)使用日期选择器呈现此输入字段。

为了正确显示日期,该值必须格式化为2012-09-28。引自说明书:

value:在[RFC 3339]中定义的有效的完整日期,以及附加的 限定年份部分为四位或四位以上数字 表示大于0的数字。

你可以使用DisplayFormat属性强制这个格式:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }

我仍然有一个问题,它传递格式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"  })
}