【问题标题】:DisplayTemplate not working for nullable DateTimeDisplayTemplate 不适用于可为空的 DateTime
【发布时间】:2013-12-06 20:12:55
【问题描述】:

下面是我为可为空的DateTime 属性创建的显示模板。我将其存储在Views\Shared\EditorTemplates 文件夹中。这个模板的名字是DisplayNullableDate.cshtml

@model DateTime?

@Html.Label("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "form-control" })

我在我的Details 页面上这样调用这个模板,但是它不起作用。我仍然得到它显示在网页上的时间。

<tr>
    <td>@Html.DisplayFor(model => model.RelationshipCode1.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate1" })</td>
    <td>@Html.DisplayFor(model => model.RelationshipCode1.RelationshipId, new { @class = "relDistCode1", maxlength = 3 })</td>
</tr>
<tr>
    <td>@Html.DisplayFor(model => model.RelationshipCode2.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate2" })</td>
    <td>@Html.DisplayFor(model => model.RelationshipCode2.RelationshipId, new { @class = "relDistCode2", maxlength = 3 })</td>
</tr>
<tr>
    <td>@Html.DisplayFor(model => model.RelationshipCode3.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate3" })</td>
    <td>@Html.DisplayFor(model => model.RelationshipCode3.RelationshipId, new { @class = "relDistCode3", maxlength = 3 })</td>
</tr>
<tr>
    <td>@Html.DisplayFor(model => model.RelationshipCode4.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate4" })</td>
    <td>@Html.DisplayFor(model => model.RelationshipCode4.RelationshipId, new { @class = "relDistCode4", maxlength = 3 })</td>
</tr>
<tr>
    <td>@Html.DisplayFor(model => model.RelationshipCode5.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate5" })</td>
    <td>@Html.DisplayFor(model => model.RelationshipCode5.RelationshipId, new { @class = "relDistCode5", maxlength = 3 })</td>
</tr>

我确实在同一个 Shared\EditorTemplates 文件夹中以 NullableDate.cshtml 的名称为同一个可为空属性提供了另一个模板。我认为这不会干扰,但无论如何我都会发布它以防万一。

@model DateTime?

@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "form-control" })

编辑

为了更好地衡量,这里是现在的模型属性。不幸的是,我也无法使用这种显示格式装饰。

    [DisplayName("Effective Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public Nullable<System.DateTime> EffectiveDate { get; set; }

【问题讨论】:

    标签: c# .net asp.net-mvc-3 razor mvc-editor-templates


    【解决方案1】:

    我认为您需要使用 [UIHint("NullableDate")] 属性来装饰模型的属性。

    【讨论】:

    • 嗯...目前没有,但NullableDate 模板可以正常工作。刚刚发布了模型属性。
    【解决方案2】:

    当我在 DateTime 字段中有空值时,此 DisplayTemplate 最终为我工作:

    @model DateTime?
    
    @((@Model != null) ?  Model.Value.ToString("MM/dd/yyyy") : "{n/a}" )
    

    值为null时,替换为字符串:{n/a}

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多