简体   繁体   English

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

[英]ASP.net MVC, custom section html helper, opening/closing divs mismatch

I have this 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);
    }
}

If footer is set to True, that means I will end panel-body myself, so on dispose it writes one less div. 如果页脚设置为True,这意味着我将自己结束面板体,所以在处置它时会减少一个div。 This should let me have panel-footer when I need it, or have table outside of body. 这应该让我在需要时使用面板页脚,或者在身体外面放置桌子。 But on when I do this I get 但是,当我这样做时,我得到了

Parser Error Message: Encountered end tag "div" with no matching start tag. 分析器错误消息:遇到结束标记“div”,没有匹配的开始标记。

My razor code looks like this: 我的剃刀代码如下所示:

    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

Obvious solution would be to simply not open panel body on that helper, and for panel body use different helper. 明显的解决方案是简单地不打开那个帮手上的面板主体,并且面板主体使用不同的帮手。 But I'm still interested why it gives me that error. 但我仍然感兴趣为什么它给了我这个错误。 It should generate good html without any errors, but it looks like it process everything before changing helper into html, sees an extra div and throws parse error. 它应该生成好的HTML而没有任何错误,但它看起来像处理所有内容之前将帮助器更改为html,看到一个额外的div并抛出解析错误。 Why is that? 这是为什么? Is there any way to make this work? 有没有办法让这项工作?

Unbalanced razor tags can be output using the @: syntax. 可以使用@:语法输出不平衡的剃刀标签。

Providing everything else compiles you can output the razor as follows: 提供其他所有编译,您可以输出剃刀如下:

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

Note the @:</div> . 注意@:</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM