我在弄清楚如何格式化我看来的日期时遇到了一些麻烦。在我的应用程序中,我有一个编辑按钮。单击后,文本框即可编辑日期值。然而,它也向我显示了我不想看到的时间。我该如何解决这个问题?
我的模型类中的代码:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Planned_Date { get; set; }
我的 View 类中的代码:
<td class="Planned_Date">
<span>@Html.DisplayFor(x=>item.Planned_Date)</span>
@Html.TextBoxFor(x => item.Planned_Date)
</td>
onClick():
$("body").on("click", "#tblCustomers .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
最佳答案
您需要编辑模型上的DataAnnotation
。
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
添加ApplyInEditMode
属性:
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}"), ApplyFormatInEditMode = true)]
这将使DataFormartString
应用于使用EditorFor
或其他编辑器生成的文本框。从这里MSDN article ,
The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.)
然后,您应该更新 View 以使用 Razor 帮助器 Html.EditorFor
,而不是在 View 中声明输入元素并设置模型中的值。引用Microsoft API了解更多信息。
<td class="Planned_Date">
<span>@Html.DisplayFor(x=>item.Planned_Date)</span>
@Html.EditorFor(x=>item.Planned_Date)
</td>
您可能需要调整示例代码以适合您的情况(例如,添加类或样式)。您的 JavaScript 应该仍然可以工作。
注意:DisplayFormat
DataAnnotation
不适用于使用 Html.TextboxFor
生成的输入。它仅适用于使用 Html.EditorFor
和 Razor Display 帮助程序生成的文本框(或其他编辑器)。
关于javascript - ASP.NET MVC 中的日期格式设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767123/