【问题标题】:MVC2: Is there an Html Helper for raw Html?MVC2:是否有原始 Html 的 Html Helper?
【发布时间】:2010-01-30 22:55:24
【问题描述】:

是否有一个简单地接受并返回原始 html 的 Html 助手?而不是做这样丑陋的事情:

<% if (Model.Results.Count > 0) { %><h2>Results</h2><% } %>

我想做这样的事情:

 <% if (Model.Results.Count > 0) { Html.RawHtml("<h2>Results</h2>") } %>

不是很干净,但我认为这是一个改进。存在这样的东西吗?或者有没有比使用 Html 助手更好的替代方法来从这些转义字符中输出原始 html?

【问题讨论】:

  • 现在我想一想,如果只使用这样的文字字符串,您将失去智能感知和 html 解析能力。有了上面这样一个简单的例子,这并不是什么大不了的事,但我想对于更复杂的 html 来说可能是这样。

标签: html asp.net-mvc-2 html-helper


【解决方案1】:

对于 MVC2:

<%: MvcHtmlString.Create("<h2>Results</h2>") %>

在这里找到:

store and display html tags in MVC

【讨论】:

    【解决方案2】:

    Response.Write 应该可以工作。 (尽管这可能有点退后一步!)您应该能够创建一个扩展方法来做到这一点。您可能希望在代码 using the TagBuilder 中构建标记,而不是使用 HTML 字符串。

    【讨论】:

      【解决方案3】:

      现在有这样的助手:

      Html.Raw("<h2>Results</h2>")
      

      【讨论】:

      • 它只在MVC3中可用,在MVC2中不可用。
      【解决方案4】:

      如果你想在任何事情上使用 HtmlHelper,你可以返回一个使用 TabBuilder 构建的 MvcHtmlString

      这是我使用的一个示例:

          public static MvcHtmlString AccountsDropDown(this HtmlHelper helper, string name,  object htmlAddributes = null, bool addNull = false, Guid? selected = null)
          {
              Account acc = HttpContext.Current.Session["account"] as Account;
      
              TagBuilder tb = new TagBuilder("select");
      
              tb.GenerateId(name);
              tb.Attributes["name"] = name;
      
              if (addNull)
                  tb.InnerHtml += string.Format("<option value= '{0}'> {1} </option>", "", "None");
      
      
              Dictionary<Guid, String> accounts;
      
              if (acc.Master)
                  accounts = db.Account.ToDictionary(x => x.Id, x => x.Name);
              else
                  accounts = db.Account.Where(x => x.Id == acc.Id).ToDictionary(x => x.Id, x => x.Name);
      
              foreach (var account in accounts)
                  tb.InnerHtml += string.Format(
                      "<option value= '{0}' {2}> {1} </option>", 
                      account.Key, 
                      account.Value,
                      selected == account.Key ? " selected='selected' " : ""
                  );
      
              return new MvcHtmlString(tb.ToString());
          }
      

      【讨论】:

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