Creating MVC3 Razor Helper like Helper.BeginForm()

It’s totally possible. The way this is done in MVC with things like Helper.BeginForm is that the function must return an object that implements IDisposable.

The IDisposable interface defines a single method called Dispose which is called just before the object is garbage-collected.

In C#, the using keyword is helpful to restrict the scope of an object, and to garbage-collect it as soon as it leaves scope. So, using it with IDisposable is natural.

You’ll want to implement a Section class which implements IDisposable. It will have to render the open tag for your section when it is constructed, and render the close tag when it is disposed. For example:

public class MySection : IDisposable {
    protected HtmlHelper _helper;

    public MySection(HtmlHelper helper, string className, string title) {
        _helper = helper;
        _helper.ViewContext.Writer.Write(
            "<div class=\"" + className + "\" title=\"" + title + "\">"
        );
    }

    public void Dispose() {
        _helper.ViewContext.Writer.Write("</div>");
    }
}

Now that the type is available, you can extend the HtmlHelper.

public static MySection BeginSection(this HtmlHelper self, string className, string title) {
    return new MySection(self, className, title);
}

Leave a Comment