DateTime字段和Html.TextBoxFor()帮助器.如何正确使用?

Lor*_*nzo 21 asp.net-mvc html-helper

我的模型中有一个DateTime字段.如果我尝试以这种方式在强类型局部视图中使用此字段

<%= Html.TextBoxFor(model => model.DataUdienza.ToString("dd/MM/yyyy"), new { style = "width: 120px" })  %>
Run Code Online (Sandbox Code Playgroud)

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

System.InvalidOperationException : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Run Code Online (Sandbox Code Playgroud)

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

我在哪里做错了?处理这个问题的正确方法是什么?

谢谢你的帮助!

编辑

这是模型类中的属性声明

[Required]
[DisplayName("Data Udienza")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DataUdienza { get; set; }
Run Code Online (Sandbox Code Playgroud)

Dar*_*MFJ 23

我在mvc 4中使用它.它也有效〜

@Html.TextBoxFor(x => x.DatePurchase, "{0:yyyy-MM-dd}", new { @class = "dateInput", @placeholder = "plz input date" })
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 19

<%= Html.EditorFor(model => model.DataUdienza) %>
Run Code Online (Sandbox Code Playgroud)

在你的模型中:

[DisplayFormat(ApplyFormatInEditMode = true, 
               DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DataUdienza { get; set; }
Run Code Online (Sandbox Code Playgroud)

EditorFor的缺点是您无法将自定义html属性应用于生成的字段.作为替代方案,您可以使用TextBox帮助程序:

<%= Html.TextBox("DataUdienza", Model.Date.ToString("dd/MM/yyyy"), new { style = "width: 120px" })%>
Run Code Online (Sandbox Code Playgroud)


Roh*_*rbs 12

创建一个名为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) %>
Run Code Online (Sandbox Code Playgroud)

将它放在Views/Shared/EditorTemplates文件夹中.现在你打电话的时候:

<%= Html.EditorFor(model => model.DataUdienza) %>
Run Code Online (Sandbox Code Playgroud)

您的DateTime将没有时间格式化.

所有以这种方式调用的DateTime都会发生这种情况,但......

可以通过以下方式使用自定义html属性:

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

它作为ViewData传递给EditorTemplate.