【问题标题】:How to concisely create optional HTML attributes with razor view engine?如何使用 razor 视图引擎简洁地创建可选的 HTML 属性?
【发布时间】:2011-04-17 13:27:00
【问题描述】:

我正在寻找一种用更少的代码行(可能是 5 行)编写以下代码的方法。我想我可以做与所选类相同的事情,但这种剃刀语法看起来并不漂亮。

<ul>
@foreach (var mi in Model.MenuItems) {
  <li@(mi.Selected?" class=\"selected\"":null)>
  @if (string.IsNullOrEmpty(mi.Title)) {
    <a href="@mi.Href">@mi.Text</a>
  } else {
    <a href="@mi.Href" title="@mi.Title">@mi.Text</a>
  }
  </li>
}
</ul>

【问题讨论】:

  • 最新版本的 razor 现在已经内置了对此的支持。请参阅下面的答案。

标签: asp.net-mvc razor viewengine


【解决方案1】:
<ul>
@foreach (var mi in Model.MenuItems) {
    <li@(mi.Selected?" class=\"selected\"":null)>
        <a href="@mi.Href" @{if(!string.IsNullOrEmpty(mi.Title)) { <text>title="@mi.Title"</text>} }>@mi.Text</a>
    </li>
}
</ul>

我没有测试它,但它解析正确。

【讨论】:

  • 哇,如果您也花时间查看错误消息,您会看到您需要做的就是在 if 块内容周围添加一个 {},您会看到我的代码产生了您正在寻找的确切输出...
  • 哎呀,我确实“查看”了错误消息并尝试了括号,但我一定没有理解该消息。 :) 感谢您更新您的帖子。
  • 抱歉,我知道这很粗鲁。早上不好。也就是说,我肯定会看看 Darin 的 html 助手,因为这基本上就是 MVC 的全部内容。
【解决方案2】:

这将是自定义 HTML 助手的理想选择:

public static class HtmlExtensions
{
    public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, MenuItem mi)
    {
        var li = new TagBuilder("li");
        if (mi.Selected)
        {
            li.AddCssClass("selected");
        }
        var a = new TagBuilder("a");
        a.MergeAttribute("href", mi.Href);
        if (!string.IsNullOrEmpty(mi.Title))
        {
            a.MergeAttribute("title", mi.Title);
        }
        a.SetInnerText(mi.Text);
        return MvcHtmlString.Create(li.ToString());
    }
}

在你看来:

<ul>
@foreach (var mi in Model.MenuItems) {
    @Html.MenuItem(mi)
}
</ul>

或者使用 DisplayTemplates 你甚至不需要编写循环:

<ul>
    @Html.DisplayFor(x => x.MenuItems)
</ul>

【讨论】:

  • 达林,你的代码很棒,但不知何故,我觉得这违背了剃刀的目的。微软需要解决这个问题。
【解决方案3】:

我想出了一个可链接的 HtmlAttribute 类和一些 Html 扩展方法,以允许使用以下 Razor 语法:

<ul> 
    @foreach (var mi in items) { 
    <li @Html.Css("selected", mi.Selected)> 
        <a href="@mi.Href" @Html.Attr("title", mi.Title)>@mi.Text</a> 
    </li> 
    } 
</ul> 

这里是 HtmlAttribute 类:

public class HtmlAttribute : IHtmlString     
{
    private string _InternalValue = String.Empty;
    private string _Seperator;

    public string Name { get; set; }
    public string Value { get; set; }
    public bool Condition { get; set; }

    public HtmlAttribute(string name)
        : this(name, null)
    {
    }

    public HtmlAttribute( string name, string seperator )
    {
        Name = name;
        _Seperator = seperator ?? " ";
    }

    public HtmlAttribute Add(string value)
    {
        return Add(value, true);
    }

    public HtmlAttribute Add(string value, bool condition)
    {
        if (!String.IsNullOrWhiteSpace(value) && condition)
            _InternalValue += value + _Seperator;

        return this;
    }

    public string ToHtmlString()
    {
        if (!String.IsNullOrWhiteSpace(_InternalValue))
            _InternalValue = String.Format("{0}=\"{1}\"", Name, _InternalValue.Substring(0, _InternalValue.Length - _Seperator.Length));
        return _InternalValue;
    }
}

额外信息:“分隔符”用于将属性的多个值链接在一起。这对于多个 css 类名(使用空格)或可能使用 String.Empty 来构建依赖于多个条件的值(通过使用 .Add() 方法)很有用

这里是 Html Extension 辅助方法:

public static class Extensions
{
    public static HtmlAttribute Css(this HtmlHelper html, string value)
    {
        return Css(html, value, true);
    }

    public static HtmlAttribute Css(this HtmlHelper html, string value, bool condition)
    {
        return Css(html, null, value, condition);
    }

    public static HtmlAttribute Css(this HtmlHelper html, string seperator, string value, bool condition)
    {
        return new HtmlAttribute("class", seperator).Add(value, condition);
    }

    public static HtmlAttribute Attr(this HtmlHelper html, string name, string value)
    {
        return Attr(html, name, value, true);
    }

    public static HtmlAttribute Attr(this HtmlHelper html, string name, string value, bool condition)
    {
        return Attr(html, name, null, value, condition);
    }

    public static HtmlAttribute Attr(this HtmlHelper html, string name, string seperator, string value, bool condition)
    {
        return new HtmlAttribute(name, seperator).Add(value, condition);
    }
}

让我知道它们是否有用。

谢谢,

李

【讨论】:

  • 您需要转义这些值。
  • 嗨,Lee,你能告诉我将这些类放在 MVC 项目中的什么位置,以及如何/在哪里引用它们吗?
【解决方案4】:
<ul>
@foreach (var mi in Model.MenuItems) {
  <li@(Html.Raw((mi.Selected ? " class=\"selected\"" : null))>
    <a href="@mi.Href">@mi.Text</a>
  </li>
}
</ul>

【讨论】:

    【解决方案5】:

    真的很简单干净:

    <p @(cssClass != null) ? { class="@cssClass" }> Stuff and whatnot... </p>
    

    【讨论】:

      【解决方案6】:

      在 ASP.NET MVC 4 中修复

      见http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx

      条件属性渲染

      如果您有一个可能为 null 的属性,过去您需要进行 null 检查以避免写出空属性,如下所示:

      <div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div>
      

      现在 Razor 能够自动处理该问题,因此您只需写出属性即可。如果为null,则不写入属性:

      <div class="@myClass">Content</div>
      

      所以如果@myClass 为空,输出就是这样:

      <div>Content</div>
      

      【讨论】:

      • 您实际上并不是指 ASP.NET 4,而是指 ASP.NET MVC 4,它在撰写本文时仍处于测试阶段 - ASP.NET 4 附带VS2010 和 .NET 4.0 并且不包含条件属性渲染。
      • 如果我想将一个样式添加到其他样式中,我该怎么做。例如,如果 bool 为真,则说 display:none。还是我还需要使用那个丑陋的条件?
      • @ppumkin 我是这样做的; var trstyle = index == 0 ? "display: none;" : null;,然后在tr 本身我做&lt;tr style="@trstyle"&gt;,这使得第一行隐藏(索引== 0)。其他行的输出只是&lt;tr&gt;。工作得很漂亮。 +1。
      【解决方案7】:

      如果值为null,Razor 将不会呈现class 属性

      <a href="#nolink" class="@(categoryId == null ? "submenu-active": null)">All</a>
      

      【讨论】:

        【解决方案8】:

        对于多个类的情况,我使用这个简单的扩展方法:

        public static MvcHtmlString If(this string text, bool condition) {
            return new MvcHtmlString(condition ? text : string.Empty);
        }
        

        在视图中:

        <div class="menuitem @("active".If(Model.Active))">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多