如何使用IDisposable禁用HtmlHelper的Html输出?

时间:2016-10-30 22:47:10

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

如何禁用剃刀页面的使用块(IDisposable HtmlHelper)中的输出?

以下是MCVE而非我的确切情况。

我有IDisposable的小帮手:

public class DisposableHelper : IDisposable
{
    private readonly Action _endAction;

    public DisposableHelper(Action beginAction, Action endAction)
    {
        _endAction = endAction;
        beginAction();
    }

    public void Dispose()
    {
        _endAction();
    }
}

这个扩展方法:

public static IDisposable BeginSupress(this HtmlHelper htmlHelper)
{
    var originalWriter = htmlHelper.ViewContext.Writer;
    return new DisposableHelper(() => htmlHelper.ViewContext.Writer = TextWriter.Null, () => htmlHelper.ViewContext.Writer = originalWriter);
}

My Razor View看起来像这样:

@using (Html.BeginSupress())
{
    <h1>This actually should have not been printed!</h1>
}

我希望没有打印任何内容,但打印出这个字符串:

<h1>This actually should have not been printed!</h1>

1 个答案:

答案 0 :(得分:0)

受到this post的不同标题的启发,我得到了答案。

似乎我们需要直接使用底层的StringBuilder。不知道为什么暂时无法交换它。

public static IDisposable BeginSupress(this HtmlHelper htmlHelper, bool suppress)
{
    StringBuilder stringBuilder = null;
    StringBuilder backupStringBuilder = null;
    return new DisposableHelper(
        () =>
        {
            if (suppress)
            {
                stringBuilder = ((StringWriter)htmlHelper.ViewContext.Writer).GetStringBuilder();
                backupStringBuilder = new StringBuilder(stringBuilder.Length).Append(stringBuilder);
            }
        },
        () =>
        {
            if (suppress)
            {
                stringBuilder.Length = 0;
                stringBuilder.Append(backupStringBuilder);
            }
        });
}