日期时间格式与编辑器模板MVC
本文关键字:MVC 编辑器 时间 格式 日期 | 更新日期: 2023-09-27 18:13:18
我想将显示在文本框中的日期时间设置为没有时间的格式:2011年1月1日,而不是显示和编辑场景的默认01/01/2011。
我已经为DateTime使用了以下模板,以便使用日期选择器。我能在这里包含格式吗?
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%: Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" }) %>
<%= Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd MMM, yyyy") : "", new { @class = "text-box single-line" }) %>
或者在视图模型上更好:
[DisplayFormat(DataFormatString = "{0:dd MMM, yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Foo { get; set; }
ViewData.TemplateInfo.FormattedModelValue
是日期时间对象吗?
要从DateTime对象中获得所需的格式,请使用以下命令:
var now = DateTime.Now;
var formattedDate = now.ToString("dd MMM, yyyy");
应该可以
<%=
var theDate = Model.HasValue ? Model.Value.ToString("dd MMM, yyyy") : DateTime.Now.ToString("dd MMM, yyyy");
Html.TextBox("", theDate, new { @class = "text-box single-line" }) %>
当你调用Model.ToString("dd MMM, yyyy")
时,你得到一个错误的原因是因为它是一个空对象,它的ToString()方法不接受任何参数。模型的值是一个DateTime对象,它不接受参数。