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


当前回答

只需在模型旁边添加。

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

其他回答

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

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

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

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

您可以使用下面的代码以HH:mm格式打印时间,在我的情况下,属性类型是TimeSpan 所以值是HH:mm:tt格式,但我必须显示在上面的格式,即。HH: mm

所以你可以使用下面的代码:

@Html.TextBoxFor(x =>x.mTimeFrom, null, new {@Value =Model.mTimeFrom.ToString().Substring(0,5), @class = "form-control success" })

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