简体   繁体   English

如何在 Razor 助手中正确呈现助手?

[英]How do I render a helper properly within a Razor helper?

Imagine this scenario...想象一下这个场景……

@helper TabTest()
{
    using (Html.BeginPortlet())
    {
        <strong>hello</strong>
    }
}

If I call it in the Razor file then it renders fine.如果我在 Razor 文件中调用它,那么它呈现得很好。

@TabTest()

Output: <div class="portlet"><strong>hello</strong></div>输出: <div class="portlet"><strong>hello</strong></div>

If I call it using another helper... eg: @Html.RenderBootstrapTabContent(TabTest()) then the rendering is not the same.如果我使用另一个助手调用它...例如: @Html.RenderBootstrapTabContent(TabTest())那么渲染就不一样了。

Output:输出:

<div class="portlet"></div>
<strong>hello</strong>

This is just a crude example and I've removed the redundant code to simplify.这只是一个粗略的例子,我删除了冗余代码以简化。 I assume it is something to do with the way the pipeline is written but I see no way to fix it.我认为这与管道的编写方式有关,但我认为没有办法修复它。

I've read things about viewcontexts and textwriters but don't know how they would apply here.我已经阅读了有关 viewcontexts 和 textwriters 的内容,但不知道它们将如何应用于这里。

The helper:帮手:

public static MvcHtmlString RenderBootstrapTabContent(this HtmlHelper helper, HelperResult content)
{
    return content.ToHtmlString();
}

The BeginPortlet method is custom and very similar to BeginForm and uses the IDisposable interface. BeginPortlet方法是自定义的,与BeginForm非常相似,并使用IDisposable接口。

What can I do to fix this weird error?我该怎么做才能解决这个奇怪的错误?

Just in case my question didn't make sense to you I found someone else who did what I was trying to explain just without calling them in the same way.以防万一我的问题对你没有意义,我找到了其他人,他做了我试图解释的事情,只是没有以同样的方式打电话给他们。 http://web.archive.org/web/20170504100102/http://jordanwallwork.co.uk/2012/07/nested-htmlhelpers-with-razor-and-using/ http://web.archive.org/web/20170504100102/http://jordanwallwork.co.uk/2012/07/nested-htmlhelpers-with-razor-and-using/

After reading everything I could online I still found no answer.在阅读了我可以在网上找到的所有内容后,我仍然没有找到答案。 It seems like perhaps nobody else has either tried this (or knew not to).似乎没有其他人尝试过(或不知道)。

I finally fixed the issue by rewriting the RenderBootstrapTabContent method in the same way as BeginPortlet using a helper and IDisposable .我最终通过使用 helper 和IDisposable以与 BeginPortlet 相同的方式重写 RenderBootstrapTabContent 方法来解决该问题。 So now instead of writing...所以现在而不是写...

@Html.RenderBootstrapTabContent(TabTest())

I now use我现在用

using (Html.BeginBootstrapTabContent()) { @TabTest() }

I've wasted a lot of time over the last few days on this so I help this might help you.过去几天我在这方面浪费了很多时间,所以我帮助这可能对您有所帮助。

If you've got a better idea please let me know.如果您有更好的主意,请告诉我。

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

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