在BeginForm风格一次性的HTML帮助捕获内容包裹 [英] Capture wrapped content in BeginForm style disposable html helper

查看:146
本文介绍了在BeginForm风格一次性的HTML帮助捕获内容包裹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写使用IDisposable的包装等code一BeginForm风格的HTML帮助。我要助手只渲染包裹code。如果一定条件满足(例如,用户是有一定的作用)。

I am trying to write a BeginForm style html helper that uses IDisposable to wrap other code. I want the helper to only render the wrapped code if a certain condition is met (e.g. user is in a certain role).

我以为我可以简单地切换context.Writer在Begin方法和切换回的Dispose方法。在code以下编译并运行,但包裹的内容被在所有情况下渲染。如果我通过它一步到位,包装的内容没有写入新的StringWriter,所以不是我的控制范围之内。

I thought that I could simply switch the context.Writer in the Begin method and switch it back in the Dispose method. The code below compiles and runs but the wrapped content gets rendered in all cases. If I step through it, the wrapped content is not written to the new StringWriter and therefore not within my control.

    public static IDisposable BeginSecure(this HtmlHelper html, ...)
    {
        return new SecureSection(html.ViewContext, ...);
    }

    private class SecureSection : IDisposable
    {
        private readonly ViewContext _context;
        private readonly TextWriter _writer;

        public SecureSection(ViewContext context, ...)
        {
            _context = context;
            _writer = context.Writer;
            context.Writer = new StringWriter();
        }

        public void Dispose()
        {
            if (condition here)
            {
                _writer.Write(_context.Writer);
            }

            _context.Writer = _writer;
        }
    }

正是我试图做可能与HTML佣工?

Is what I am trying to do possible with html helpers?

我知道,在剃刀声明HTML辅助可能会工作,但将preFER标准的HTML辅助方法,如果可能的话,鉴于MVC3剃刀佣工的APP_ code限制。

I know that declarative html helpers in razor would probably work but would prefer standard html helper approach if possible, given the app_code limitation of razor helpers in MVC3.

推荐答案

您不能有条件地呈现helper方法返回的IDisposable 的主体内容。它总是呈现。当你想使用一些自定义的标记来包装使用块体,如 BeginForm 助手就是与<形式的方式> 元素

You can't conditionally render the body contents of a helper method returning IDisposable. It will always render. You could use this style of helpers when you want to wrap the body of the using block with some custom markup such as the BeginForm helper does with the <form> element.

您可以使用 模板剃须刀委托 来代替:

You could use a templated Razor delegate instead:

public static class HtmlExtensions
{
    public static HelperResult Secure(this HtmlHelper html, Func<object, HelperResult> template)
    {
        return new HelperResult(writer =>
        {
            if (condition here)
            {
                template(null).WriteTo(writer);
            }
        });
    }
}

和则:

@Html.Secure(
    @<div>
         You will see this text only if some condition is met
    </div>
)

这篇关于在BeginForm风格一次性的HTML帮助捕获内容包裹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆