【问题标题】:ASP.Net MVC DisplayFormatASP.Net MVC 显示格式
【发布时间】:2010-01-04 19:52:23
【问题描述】:

在我的模型中,我的一个属性上有以下 DataAnnotations

[Required(ErrorMessage = "*")]
[DisplayFormat(DataFormatString = "{0:d}")]
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }

所需的注释效果很好,我添加了其他 2 个以尝试删除时间。它使用

绑定到视图中的输入
<%=Html.TextBoxFor(m => m.Birthdate, new { @class = "middle-input" })%>

但是,每当加载视图时,我仍然会在输入框中显示时间。有没有办法使用 DataAnnotations 删除它?

【问题讨论】:

标签: asp.net-mvc data-annotations


【解决方案1】:

[DisplayFormat] 属性仅在 EditorFor/DisplayFor 中使用,而在 TextBoxFor 等原始 HTML API 中不使用。

【讨论】:

  • 我使用的是 MVC4 Razor 语法,日期字段呈现为@Html.EditorFor(m =&gt; m.IssueDate),模型上的格式应用为[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}" )],但日期仍显示为01/01/0001 12:00:00 AM
  • @bjan 您是否设置了ApplyFormatInEditMode 属性?
【解决方案2】:

正如 Brad 所说,它不适用于 TextBoxFor,但如果您希望它适用于 EditorFor,您还需要记住添加 ApplyFormatInEditMode。

[DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )]
public System.DateTime DateCreated { get; set; }

然后使用

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

【讨论】:

  • EditorFor 让我失望了。我有 TextBoxFor - 适用于其他格式,例如数字或标签。 +1
【解决方案3】:

我的问题是设置一些 html 属性(jquery-datepicker),所以 EditorFor 对我来说是没有选择的。

实现自定义帮助方法解决了我的问题:

具有日期时间属性的模型类:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime CustomDate{ get; set; }

以 ModelClass 作为模型查看:

@Html.TextBoxWithFormatFor(m => m.CustomDate, new Dictionary<string, object> { { "class", "datepicker" } })

静态助手类中的Helper-Methode:

public static class HtmlHelperExtension {
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.TextBox(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(metadata.PropertyName), string.Format(metadata.DisplayFormatString, metadata.Model), htmlAttributes);
    }
}

【讨论】:

  • 如果您只是为 DateTime 创建一个编辑器模板来执行您需要它执行的操作,您可以继续使用 EditorFor。编辑器模板很好,因为您可以从视图中请求一个编辑器,而不必过多了解您将获得什么,并且您可以通过更改编辑器模板随意更改所有编辑器以用于不同的控件。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 2012-09-23
  • 2013-08-19
  • 1970-01-01
  • 2019-02-10
  • 2022-10-20
  • 1970-01-01
相关资源
最近更新 更多