我正在使用数据类型。模型中的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>
我仍然有一个问题,它传递格式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" })
}
在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)
}
回复MVC4数据类型。日期编辑器在Chrome中不会显示日期值,在IE中没问题
在模型中,你需要有以下类型的声明:
[DataType(DataType.Date)]
public DateTime? DateXYZ { get; set; }
OR
[DataType(DataType.Date)]
public Nullable<System.DateTime> DateXYZ { get; set; }
你不需要使用以下属性:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
约会时。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" })
}
}
玩得开心!
问候,
Blerton