我正在尝试编写一个 BeginForm 样式的 html 助手,它使用 IDisposable 来包装其他代码。我希望助手仅在满足特定条件时才呈现包装代码(例如,用户处于特定角色)。
我认为我可以简单地在 Begin 方法中切换 context.Writer 并在 Dispose 方法中将其切换回。下面的代码编译并运行,但在所有情况下都会呈现包装的内容。如果我单步执行,则包装的内容不会写入新的 StringWriter,因此不在我的控制范围内。
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 助手做的事情吗?
我知道 razor 中的声明性 html 助手可能会起作用,但如果可能的话,我会更喜欢标准的 html 助手方法,因为 MVC3 中 razor 助手的 app_code 限制。