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).
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;
}
}
Is what I am trying to do possible with html helpers?
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.
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 theusingblock with some custom markup such as theBeginFormhelper does with the<form>element.You could use a
templated Razor delegateinstead:and then: