我在使用TextBoxFor<,>(表达式,htmlAttributes)将DateTime的唯一日期部分显示为文本框时遇到了麻烦。

该模型基于Linq2SQL,字段是SQL和实体模型中的DateTime。

失败:

<%= Html.TextBoxFor(model => model.dtArrivalDate, String.Format("{0:dd/MM/yyyy}", Model.dtArrivalDate))%>

这个技巧似乎被贬低了,htmlAttribute对象中的任何字符串值都被忽略了。

失败:

[DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}" )]
public string dtArrivalDate { get; set; }

我想在详细信息/编辑视图上只存储和显示日期部分,而没有“00:00:00”部分。


当前回答

如果你坚持使用[DisplayFormat],但你没有使用MVC4,你可以使用这个:

@Html.TextBoxFor(m => m.EndDate, new { Value = @Html.DisplayFor(m=>m.EndDate), @class="datepicker" })

其他回答

模板编辑器仅用于显示目的。 如果你使用相同的编辑器(这是有意义的,因为它是一个编辑器),并且你提供了一个像31/01/2010这样的值,你会得到一个错误消息,说格式无效。

在初始加载时,DisplayFormat属性在两种形式中都不能为我工作。我创建了一个EditorTemplate:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%=
    Html.TextBox("", Model.ToShortDateString(), new { @class = "date-range" }) %>
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

然后:

<%=Html.EditorFor(m => m.StartDate) %>

对我来说,我需要保留TextboxFor(),因为使用EditorFor()将输入类型更改为日期。在Chrome中,添加了一个内置的日期选择器,这把我已经在使用的jQuery日期选择器搞砸了。因此,继续使用TextboxFor(),只输出日期,你可以这样做:

<tr>
    <td class="Label">@Html.LabelFor(model => model.DeliveryDate)</td>
    @{
        string deliveryDate = Model.DeliveryDate.ToShortDateString();
    }
    <td>@Html.TextBoxFor(model => model.DeliveryDate, new { @Value = deliveryDate }) *</td>
    <td style="color: red;">@Html.ValidationMessageFor(model => model.DeliveryDate)</td>
</tr>
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>