Ben*_*kel 197 asp.net-mvc editorfor asp.net-mvc-4
我在我的模型中使用DataType.Date属性,在我的视图中使用EditorFor.这在Internet Explorer 8和Internet Explorer 9中运行良好,但在谷歌浏览器中它显示日期选择器,而不是显示值,它只是在褪色的灰色文本中显示"月/日/年".
为什么Google Chrome不会显示价值?
模型:
[DataType(DataType.Date)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
Run Code Online (Sandbox Code Playgroud)
视图:
<td class="fieldLabel">Est. Pur. Date</td>
<td class="field">@Html.EditorFor(m=>m.EstPurchaseDate)</td>
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 374
[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" />
Run Code Online (Sandbox Code Playgroud)
支持HTML5的浏览器(例如Google 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; }
Run Code Online (Sandbox Code Playgroud)
Cha*_*lie 42
在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)
}
Run Code Online (Sandbox Code Playgroud)
Arj*_*jan 16
作为Darin Dimitrov回答的补充:
如果您只希望此特定行使用某种(不同于标准)格式,则可以在MVC5中使用:
@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })
Run Code Online (Sandbox Code Playgroud)
Azo*_*oro 11
在MVC 3中,我不得不添加:
using System.ComponentModel.DataAnnotations;
Run Code Online (Sandbox Code Playgroud)
在添加属性时使用:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Run Code Online (Sandbox Code Playgroud)
特别是如果你像我这样在.edmx文件中添加这些属性.我发现默认情况下.edmx文件没有这个使用,所以只添加propeties是不够的.