c# – ASP.net MVC,自定义部分html助手,打开/关闭div不匹配

我有这个帮手:

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

如果页脚设置为True,这意味着我将自己结束面板体,所以在处置它时会减少一个div.这应该让我在需要时使用面板页脚,或者在身体外面放置桌子.但是,当我这样做时,我得到了

Parser Error Message: Encountered end tag “div” with no matching start tag.

我的剃刀代码如下所示:

    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而没有任何错误,但它看起来像处理所有内容之前将帮助器更改为html,看到一个额外的div并抛出解析错误.这是为什么?有没有办法让这项工作?

解决方法:

可以使用@:语法输出不平衡的剃刀标签.

提供其他所有编译,您可以输出剃刀如下:

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# – 模型绑定器不会填充嵌套列表中的项目


下一篇:c# – 在ASP.NET MVC中编写表单的最佳方法是什么?