【问题标题】:Input with date format set from ViewModel and html class attribute从 ViewModel 和 html 类属性设置的日期格式输入
【发布时间】:2011-11-11 12:40:45
【问题描述】:

我正在使用 asp.net mvc3 中的 razor 视图引擎。

现在,我需要一个 DateTime 的输入,它应该以固定格式显示值(比如 dd-MMM-yyyy)。所以我可以这样做:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime StartDate { get; set; }

在视图中:

@Html.EditorFor(model => model.StartDate)

但我需要在输入中添加一个类。我认为在EditorFor 中是不可能的。 所以我可以使用

@Html.TextBoxFor(model => model.StartDate, new { @class = "Date" })

但是这种情况下显示格式不起作用。

Model 可以为空。所以,

@Html.TextBox("StartDate", string.Format("{0:dd-MMM-yyyy}", Model.StartDate))

将抛出NullReferenceException

【问题讨论】:

  • 为什么第一个不能添加类??? @Html.TextBoxFor(model => model.StartDate, new { @class = "Date" })你的日期可以返回空值吗?我认为例外是因为你的日期可能为空
  • 感谢ApplyFormatInEditMode。我错过了那个参数。

标签: asp.net-mvc-3 razor editorfor date-formatting


【解决方案1】:

ophelia 的方式是我的一个更快的版本。但如果您的应用程序中有几个日期字段,这种方法很有用。所以这就是我喜欢的方式:

-> 在您的 solution explorer 中,inside Shared 创建一个名为“EditorTemplates”的文件夹

-> 在其中添加一个新的(强类型)局部视图。称之为“DateTime”。

-> 打开这个视图,去掉里面的所有代码,然后把下面的代码扔进去:

@model System.DateTime
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date" /* + any other html attributes you want */ })

-> 在您的 ViewModel 中,您的日期字段应该是这样的:

[Display(Name = "My Date:"), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }

-> 在您的主视图中,以及您想使用日期字段的任何视图中,您可以在属性上使用EditorFor,如下所示:

@Html.EditorFor(m => m.MyDate)

您可以在控制器中初始化日期字段或在视图模型的构造函数中设置默认日期。

【讨论】:

  • 很好的答案,尽管您甚至不需要 DateTime EditorTemplate,除非您为 DateTime EditorFor 添加自定义类。您只需要在 ViewModel 或 Model 中使用 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")] 并且 @Html.EditorFor(model => model.MyDateTime) 将按照您定义的方式进行格式化它在 DisplayFormat 属性中。
【解决方案2】:

我使用它并且它工作正常:

    @Html.TextBox("ExpiryDate", String.Format("{0:ddd, dd MMM yyyy}", DateTime.Now), new { id = "expirydate" })

希望这是你的意思/需要:)

【讨论】:

  • 在不使用帮助器的情况下如何格式化日期?如:@Model.ExpiryDate
猜你喜欢
  • 2011-10-22
  • 1970-01-01
  • 2020-07-10
  • 2020-03-22
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多