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


当前回答

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

其他回答

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

或者使用非类型化的helper:

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

// datePicker中的datatimetime显示为11/24/2011 12:00:00 AM

//你可以用空格分隔,只设置日期值

脚本:

    if ($("#StartDate").val() != '') {
        var arrDate = $('#StartDate').val().split(" ");
        $('#StartDate').val(arrDate[0]);
    }

标记:

    <div class="editor-field">
        @Html.LabelFor(model => model.StartDate, "Start Date")
        @Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
    </div>

希望这能有所帮助。

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

@Html.TextBoxFor(m => m.EndDate, new { Value = @Html.DisplayFor(m=>m.EndDate), @class="datepicker" })
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

然后:

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