asp.net-mvc – DateTime字段和Html.TextBoxFor()帮助器 如何正确使用?

我的模型中有一个DateTime字段。如果我以这种方式在强类型的部分视图中尝试使用此字段
<%= Html.TextBoxFor(model => model.DataUdienza.ToString("dd/MM/yyyy"),new { style = "width: 120px" })  %>

我将在运行时收到以下编译错误

system.invalidOperationException : Templates can be used only with field access,property access,single-dimension array index,or single-parameter custom indexer expressions.

无论如何,如果我使用它去除格式化,ToString(“dd / MM / yyyy”),一切正常,但字段格式化使用的时间部分,我根本不需要。

我在做错什么?这是正确的处理方法

谢谢帮忙!

编辑

这是模型类中的属性声明

[required]
[displayName("Data Udienza")]
[DataType(DataType.Date)]
[displayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DataUdienza { get; set; }

解决方法

创建一个名为DateTime.ascx的编辑器模板
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("",(Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty),ViewData) %>

将其放在您的Views / Shared / EditorTemplates文件夹中。现在当你打电话:

<%= Html.EditorFor(model => model.DataUdienza) %>

您的DateTime将被格式化,没有时间。

这将发生在所有DateTimes这样称呼,虽然…

自定义html属性可以这样使用:

<%= Html.EditorFor(model => model.DataUdienza,new {customAttr = "custom",@class = "class"}) %>

它作为ViewData传递给EditorTemplate。

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...