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


当前回答

在ASP中使用标签助手时。NET Core,格式需要在ISO格式中指定。如果没有这样指定,绑定的输入数据将不能正常显示,将显示为没有值的mm/dd/yyyy。

模型:

[Display(Name = "Hire")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? HireDate { get; set; }

观点:

<input asp-for="Entity.HireDate" class="form-control" />

格式也可以在视图中使用asp-format属性指定。

生成的HTML将如下所示:

<input class="form-control" type="date" id="Entity_HireDate" 
    name="Entity.HireDate" value="2012-01-01">

其他回答

这对我很管用。

@Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { size = "12", @class = "DOB", tabindex = 121 })
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

然后:

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

或者使用非类型化的helper:

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

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

您可以使用下面的代码以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" })