我在使用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”部分。


当前回答

或者使用非类型化的helper:

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>

其他回答

在初始加载时,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" }) %>

我使用Globalize,所以工作与许多日期格式,所以使用以下:

@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")

这将自动调整日期格式到浏览器的地区设置。

不要害怕使用原始HTML。

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>

对我来说,我需要保留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>