我有这个 helper :

public class PanelSection : IDisposable
{
    protected HtmlHelper _helper;
    private string f;
    public PanelSection(HtmlHelper helper, string title, string subTitle, bool footer)
    {
        _helper = helper;
        f = footer ? "" : "</div>";        //If footer is true, we end body ourselves, if footer is false, we end both - body and panel automatically

        _helper.ViewContext.Writer.Write(
            "<div class='panel panel-default'><div class='panel-heading'><h2>" + title + "</h2></div><div class='panel-body'>"
        );
        if (!string.IsNullOrEmpty(subTitle))
            _helper.ViewContext.Writer.Write(
            "<h4>" + subTitle + "</h4><hr/>"
        );
    }

    public void Dispose()
    {
        _helper.ViewContext.Writer.Write("</div>" + f);
    }
}

如果footer 设置为True,那意味着我将自己结束panel-body,因此在dispose 时它会少写一个div。这应该让我在需要时有面板页脚,或者在 body 外面有 table 。但是当我这样做时,我得到



我的 Razor 代码如下所示:
    using (Html.BeginPanel(@Resources.Contract, @Resources.CreateNew, true))
{ //starts panel, starts panel body
    <b>Body content</b>
    </div> //end of body
    <div class="panel-footer">
        <a href="@Url.Action("Index")" class="btn btn-default" role="button">@Resources.Back</a>
    </div>
 } //end of panel

明显的解决方案是简单地不打开该助手上的面板主体,并且对于面板主体使用不同的助手。但我仍然感兴趣为什么它会给我那个错误。它应该生成没有任何错误的良好 html,但看起来它在将 helper 更改为 html 之前处理了所有内容,看到一个额外的 div 并抛出解析错误。这是为什么?有什么办法可以使这项工作?

最佳答案

可以使用 @: 语法输出不平衡的 Razor 标签。

提供所有其他编译,您可以按如下方式输出 Razor :

using (Html.BeginPanel(@Resources.Contract, @Resources.CreateNew, true))
{
   //starts panel, starts panel body
   <b>Body content</b>
   @:</div> //end of body
   <div class="panel-footer">
      <a href="@Url.Action("Index")" class="btn btn-default" role="button">@Resources.Back</a>
  </div>
} //end of panel

注意 @:</div>

关于c# - ASP.net MVC,自定义部分 html 助手,打开/关闭 div 不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31938477/

10-11 22:31
查看更多