asp.net-mvc-5 Disposable Helper (like Html.BeginForm)


Example

  1. First create a disposable class:
public class MyDisposableHelper: IDisposable
{
   private bool _disposed;        
   private readonly ViewContext _viewContext;

    public MyDisposableHelper(ViewContext viewContext)
    {
        if (viewContext == null)
        {
            throw new ArgumentNullException(nameof(viewContext));
        }            
        _viewContext = viewContext;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;
        _disposed = true;            
        _viewContext.Writer.Write("</div>");
    }

    public void EndForm()
    {
        Dispose(true);
    }
 }

This class inherits IDisposable because we want to use the helper like Html.BeginForm(...). When disposed it closes the div created when we called the helper in the view.

  1. Create the HtmlHelper extension method:
public static MyDisposableHelper BeginContainingHelper(this HtmlHelper htmlHelper) 
{
     var containingTag = new TagBuilder("div");
     //add default css classes, attributes as needed
    htmlHelper.ViewContext.Writer.Write(containingTag .ToString(TagRenderMode.StartTag)); 
    return new MyDisposableHelper (htmlHelper.ViewContext);
}

What to notice here is the call to Writer.Write to write to the response page out custom element. The TagRenderMode.StartTag is used to inform the writer not to close the div just yet, because we are gonna close it when disposing the MyDisposableHelper class.

  1. To use it in the view:
@using (Html.BeginContainingHelper()) {
    <div>element inside our custom element</div>
}