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


当前回答

[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

然后:

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

其他回答

不要害怕使用原始HTML。

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />

或者使用非类型化的helper:

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

然后:

<%=Html.EditorFor(m => m.StartDate) %>
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>

当然你可以使用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);
    }
}