1

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?

Jason N. Gaylord
  • 7,910
  • 15
  • 56
  • 95

1 Answers1

1

Have you looked into delegated razor templates?

tulde23
  • 398
  • 1
  • 6
  • That allows me to set a template for the content, but it doesn't allow me alter the contents of the template. The contents are read into the Helper's TextWriter. – Jason N. Gaylord Mar 17 '14 at 17:29