【问题标题】:Editor Template does not work with DisplayFormat编辑器模板不适用于 DisplayFormat
【发布时间】:2012-08-22 22:54:03
【问题描述】:

我正在尝试为 DateTime 字段创建编辑器模板,但它似乎不尊重我的 DisplayFormat 属性。

我的模特:

public class Project
{
    [Display(Name="Project Name")]
    [Required]
    public string ProjectName { get; set; }

    [Display(Name="Start Date")]
    [DisplayFormat(DataFormatString="{0:M/d/yyyy}", ApplyFormatInEditMode=true)]
    public DateTime? StartDate { get; set; }
}

文件夹 /Views/Projects/EditorTemplates/DateTime.cshtml 中的我的编辑器模板

@model DateTime?
@Html.TextBoxFor(m => Model, new { @class="datepicker" })

这是将所有内容联系在一起的视图:

@model Project

<fieldset>
    <legend>Project</legend>

    <div class="editor-label">
        @Html.LabelFor(m => m.ProjectName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(m => m.ProjectName)
        @Html.ValidationMessageFor(m => m.ProjectName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(m => m.StartDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(m => m.StartDate)
        @Html.ValidationMessageFor(m => m.StartDate)
    </div>
</fieldset>

当我以这种方式获得它时,我会看到日期的时间部分。当我删除编辑器模板时,它工作正常,只显示日期部分。为什么当我有编辑器模板时它似乎忽略了 DisplayFormat?

【问题讨论】:

标签: .net asp.net-mvc asp.net-mvc-3 mvc-editor-templates


【解决方案1】:

让我们先看看不使用模板时会发生什么。我添加了泛型类型,以使其更明确的区别是什么。

@Html.TextBoxFor<Product>(product => product.StartDate)

现在让我们看看你的模板编辑器:

@Html.TextBoxFor<DateTime?>(dateTime => dateTime)

注意到区别了吗?在后一种情况下,您只是在处理 DateTime 实例,这意味着您正在丢失模型属性定义的元数据。

通过使用模板,您是负责处理元数据的人,这些元数据应在ViewData.ModelMetadata.* 中提供给您的模板。例如,在您的情况下,您需要使用ViewData.ModelMetadata.DisplayFormatString自己格式化日期

【讨论】:

  • 那么解决办法是什么?如何使用 ViewData.ModelMetadata.DisplayFormatString 自己格式化日期?请举例。
  • Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class="datepicker" }) - "" 表示当前型号。
【解决方案2】:

如果您将编辑器模板更改为:

,则将应用 DisplayFormat
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "datePicker" })

要使您的日期属性符合 HTML5,请将 DataType.Date 属性添加到您的模型属性:

[DataType(DataType.Date)]
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString="{0:M/d/yyyy}", ApplyFormatInEditMode=true)]
public DateTime? StartDate { get; set; }

并在 /Views/Projects/EditorTemplates/Date.cshtml 处添加日期编辑器模板:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "datePicker", type = "date" })

【讨论】:

    【解决方案3】:

    更改为@Html.TextBoxFor(m =&gt; m, new { @class="datepicker" })

    【讨论】:

    • 想把你的解决方案发给我吗?
    • github.com/hazzik/beerconf-website/blob/master/src/Web/Views/… 但我没有使用 DataAnnotations 来生成模型元数据,但它应该完全相同。请注意,settings.ToHtmlAttributes() 只是用于生成其他 html 属性的粘合剂,如您的示例中的new { @class="datepicker" }
    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多