扩展DisplayTemplates

时间:2015-05-04 21:19:38

标签: c# asp.net asp.net-mvc razor

我目前有一个(工作)DisplayTemplate,如下所示:

@model string
@{
    string icon = "tasks";
    string colour = "red";
    string title = "Not Started, Set or Looked at Yet";

    switch (Model)
    {
        case "None":
            icon = "ban-circle";
            colour = "green";
            title = "Chosen not to be implemented";
            break;
        case "Implemented":
            icon = "check";
            colour = "green";
            title = "Implemented";
            break;
        case "Unable to Implement":
            icon = "remove-circle";
            colour = "green";
            title = "Unable to Implement for Technical or Contract Reasons";
            break;
    }

    <span class="glyphicon glyphiconbig glyphicon-@icon @colour" title="@title"></span>
}

这很好用。在实例化此代码的页面中,我正在生成一个表并使用foreach循环。我想要做的是从我的模型中插入一些其他数据到这里。如果我只是在页面中我能做到:

@Html.DisplayFor(modelItem => item.Comment)

这在DisplayTemplate中是不可能的(我尝试在显示模板中弄乱模型语法,但我只是破坏了东西)。我怎样才能在DisplayTemplate中实现最佳效果?

1 个答案:

答案 0 :(得分:0)

如果有更多细节,使用Html.DisplayFor

additionalViewData重载很容易传递替代文字

所以,我们有视图模型......

class MyViewModel
{
    [UIHint("CommentIcon")]
    public String Comment { get; set; }
}

哪个传递给我们的观点...

@model MyViewModel
@* Other Stuff *@
@Html.DisplayFor(x => x.Comment, new { alt = "Comment Alt Test" });

在我们的展示广告模板(~/Views/Shared/DisplayTemplates/CommentIcon.cshtml)中:

@model string
@{
  string alt = ((String)ViewData["alt"]) ?? String.Empty;
  string icon = "tasks";
  string colour = "red";
  string title = "Not Started, Set or Looked at Yet";

  switch (Model)
  {
    case "None":
      icon = "ban-circle";
      colour = "green";
      title = "Chosen not to be implemented";
      break;
    case "Implemented":
      icon = "check";
      colour = "green";
      title = "Implemented";
      break;
    case "Unable to Implement":
      icon = "remove-circle";
      colour = "green";
      title = "Unable to Implement for Technical or Contract Reasons";
      break;
  }

  <span class="glyphicon glyphiconbig glyphicon-@icon @colour" title="@title" alt="@alt"></span>
}

如果您不想提供<span>属性,也可以使用TagBuilder动态构建alt

就访问原始模型而言,你不会。这将创建显示模板与特定模型的紧密耦合。请记住,您希望这些视图是自包含的,服务器只需要一个[可重用]目的。