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


当前回答

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

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

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

其他回答

当然你可以使用Html.EditorFor。 但是如果你想使用TextBoxFor和使用DisplayFormat属性的格式,你可以这样使用它:

@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)

或创建下一个扩展:

public static class HtmlExtensions
{
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
    }
}

你也可以通过应用这个数据注释来使用HTML 5属性:

[DataType(DataType.Date)]

但问题是,这为HTML 5浏览器启用了特定于浏览器的日期选择器。对于不支持日期选择器的浏览器,您仍然需要自己的日期选择器,然后您必须确保您的日期选择器不会在浏览器的日期选择器之外出现(Modernizr可以轻松地做到这一点),或者隐藏浏览器的日期选择器(很复杂,我不知道我看到的方法有多可靠)。

最后我选择了Alex的,因为我目前的环境没有Modernizr,但是如果有的话,如果浏览器还不支持的话,我就会有条件地使用它来显示我的数据选择器。

只需在模型旁边添加。

[DataType(DataType.Date)]
public string dtArrivalDate { get; set; }

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

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