【问题标题】:Extending DisplayTemplates扩展显示模板
【发布时间】:2015-05-05 05:58:47
【问题描述】:

我目前有一个(工作的)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 中最好地实现这一点?

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • DisplayFor 有一个 overload,它接受 additionalData(这将是向您的 DisplayTemplate 传递更多信息的绝佳机会。)
  • 布拉德,我不确定我是否遵循 - 你能举个例子吗?由于我无法在显示模板中引用当前模型迭代?
  • 哦,您要从 DisplayTemplate 反向引用模型?
  • 确实!具体来说,我想在我的跨度上写入一个 alt 属性,但不确定如何从显示模板访问模型。

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


【解决方案1】:

考虑到更多细节,使用 additionalViewData 重载 Html.DisplayFor 可以轻松传递 alt 文本

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

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>
}

如果您想在未提供 alt 属性的情况下保留它,也可以使用 TagBuilder 动态构建 &lt;span&gt;

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

【讨论】:

  • 这是在布拉德身上发现的,谢谢 - 有时它只是有助于拥有第二双眼睛!我假设您的 : String.Empty 语法是 C#6,因为它在我的代码中不起作用,但无论如何都能修复。
  • 糟糕,应该是??。脑子放屁,虽然我只会说它是 C#6。 ;-)
猜你喜欢
  • 2011-05-02
  • 2017-11-05
  • 2013-02-01
  • 1970-01-01
  • 2015-11-24
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多