【问题标题】:conditional check with razor用剃刀进行条件检查
【发布时间】:2013-11-08 17:12:24
【问题描述】:

在我的 MVC 视图中,我需要在模型对象中显示值。

@model List<School.Model.Student_Model>

我在表格中显示了这些学生数据。

@foreach (var item in Model)
{
    <tr>
        ...
        <td>@Html.DisplayFor(model => item.RegisterDate)</td>
    </tr>            
}

RegisterDate 可以为空DateTime?

如果 RegisterDate 为空,我喜欢在我的表格中显示消息 “未提供日期”

<td>@Html.DisplayFor(model => item.RegisterDate.HasValue?item.RegisterDate.HasValue.ToString():"-")</td>

如果我在上面使用它会给我以下错误

异常详情:System.InvalidOperationException:模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式。

如果我使用单独的 If-else 条件,我将能够做到这一点。

@if(item.RegisterDate.HasValue)
{
    <td>@Html.DisplayFor(model => item.RegisterDate)</td>
}
else
{
    <td>date is not provided</td>
}

有什么办法吗?

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:

    您可以为空字段定义一个空模板:

    //EmptyTemplate.cshtml
    @(Model == null ? "NULL" : Model)
    

    并在您的 DisplayFor 方法中调用它:

    @Html.DisplayFor(model => item.RegisterDate, "EmptyTemplate")
    

    【讨论】:

      【解决方案2】:

      DisplayTemplatesEditorTemplates 必须根据模型类型的名称命名(MyClass 模型需要 MyClass.cshtml 作为 DisplayTemplate)。尽管您不能在文件名中添加?&lt;&gt;,但它对可空类型的工作方式相同。在名为DateTime.cshtmlViews\Shared\DisplayTemplates 文件夹中创建DisplayTemplate

      @model DateTime?
      
      @(Model.HasValue ? string.Format("{0:yyyy-MM-dd}", Model.Value) : "date is not provided")
      

      它可以像这样在你的视图中使用:

      @Html.DisplayFor(model => item.RegisterDate)
      

      您不必指定模板的名称,它会按照约定找到。

      【讨论】:

        猜你喜欢
        • 2012-12-10
        • 2023-03-19
        • 1970-01-01
        • 2016-04-29
        • 1970-01-01
        • 1970-01-01
        • 2011-08-05
        • 1970-01-01
        相关资源
        最近更新 更多