Mvc UserControl使用HtmlHelper和HelperResult以及MvcHtmlString

时间:2014-10-14 14:07:58

标签: c# .net asp.net-mvc html-helper

我正在使用asp mvc开发一个应用程序,我想为开发人员创建一些友好的控件,比如asp.net WebForms中的Server控件。在这种情况下,我想创建一个具有一些固定html并在项目模板内渲染的引导面板。我是这样做的:

public static MvcHtmlString BootPanel<T>(this IEnumerable<T> items, Func<T, HelperResult> template, string title = "")
    {

     StringBuilder sb = new StringBuilder();
     sb.Append("<div class='panel panel-info'>");
     sb.Append("<div class='panel-heading'>");
     sb.Append(title);
     sb.Append("</div>");
     sb.Append("<div class='panel-body'>");

     var hr = new HelperResult(writer =>
              {
                 foreach (var item in items)
                {
                  template(item).WriteTo(writer);
                }
       });

      sb.Append(hr.ToHtmlString());
      sb.Append("</div>");
      sb.Append("</div>");
      return MvcHtmlString.Create(sb.ToString());
    }

这是剃须刀视图:

@{
  var videoGames = new[] {
      new VideoGame {nombre = "Shadows of mordor", precio = 66},
      new VideoGame {nombre = "Spiderman", precio = 50}
      };
   }    

  @videoGames.BootPanel(@<div>
                            @item.nombre  &nbsp;  @item.precio
                        </div>
                      , "Titulo")

使用引导类正确呈现输出:

enter image description here

问题是。这是实现这种控制的正确方法吗?

修改

根据你的回答我更新了帮助你使用TagBuilder:

public static MvcHtmlString BootPanel<T>(this IEnumerable<T> items, Func<T, HelperResult> template, string title = "")
    {
        TagBuilder PanelDiv = new TagBuilder("div");
        PanelDiv.AddCssClass("panel panel-info");

        TagBuilder PanelHeading = new TagBuilder("div");
        PanelHeading.AddCssClass("panel-heading");
        PanelHeading.SetInnerText(title);

        TagBuilder PanelBody = new TagBuilder("div");
        PanelBody.AddCssClass("panel-body");

        var hr = new HelperResult(writer =>
        {


            foreach (var item in items)
            {
                template(item).WriteTo(writer);
            }

        });

        PanelBody.InnerHtml = hr.ToHtmlString();

        PanelDiv.InnerHtml = PanelHeading.ToString() +
                             PanelBody.ToString();

        return MvcHtmlString.Create(PanelDiv.ToString());
    }

1 个答案:

答案 0 :(得分:1)

确保在返回之前对输出字符串进行编码,因为如果有人为标题编写javascript,则会导致脚本注入。除了看起来,但使用硬编码标签,您可以使用TagBuilder类来构建您的HTML代码。请参阅此example