I'm building a custom HtmlHelper for MVC. I'd like to allow the user to add a block of HTML that will be used with the helper. So, I'm planning on having something similar to the following in my view:
@using (Html.MyHelper())
{
// foo
}
The MyHelper helper method is defined similar to the following:
public static MyHelperWriter MyHelper(this HtmlHelper helper)
{
helper.ViewContext.Writer.Write(@"<span>");
return new MyHelperWriter(helper.ViewContext.Writer);
}
public class MyHelperWriter : IDisposable
{
private bool disposed;
public TextWriter Writer { get; set; }
public MyHelperWriter(TextWriter writer)
{
/// TODO: Modify the TextWriter stream
Writer = writer;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
this.disposed = true;
Writer.Write(@"</span>");
}
}
}
What I'd like to do is update the TextWriter stream to capture it and do something to the contents. I know I can flush the stream, but I may want to override the behavior.
If this cannot be done (and seems icky), is there a better way to accomplish this same thing?