How to Build HTML Helpers like Html.BeginForm() in ASP.NET MVC

If you’ve used ASP.NET MVC for more than five minutes, you’ve probably used the Html.BeginForm helper method.


@using (Html.BeginForm()) {
// Form Fields go here
}

This method wraps your content in a form tag. It’s a handy way to build forms, but we can also create our own html helpers for other container elements. In this post, I’m going to show you how to wrap a Bootstrap row in an HTML helper.

Bootstrap, the UI library that comes with .NET, makes it easy to build professional looking web applications. One of it’s primary disadvantages, however, is that you have to write a lot of markup to get your layouts to work correctly. We can reduce this by creating a custom HTML Helper that works like Html.BeginForm().


@using (Html.BeginRow()) {
// Grid content goes here
}

Step 1

Create a Private Class that implements IDisposable. Have the constructor take a TextWriter object. Set the dispose method to use the text writer to output the closing tag for the row.


private class RowContainer : IDisposable {
    private readonly TextWriter _writer;

    public RowContainer(TextWriter writer) {
        _writer = writer;
    }

    public void Dispose()
    {
        _writer.Write("</div>");
    }
}

Step 2:

Create an HTML helper extenstion method that creates the beginning tag and returns the object created in Step 1. You can use ViewContext.Writer to directly output the markup.


public static IDisposable BeginRow(this IHtmlHelper htmlHelper, string cssClass = "") {
    var writer = htmlHelper.ViewContext.Writer;
    writer.WriteLine(string.Format("<div class='row{0}'>", cssClass));
    return new RowContainer(writer);
}
 

Step 3

Use the helper in your Razor view with a using statement, just like BeginForm(). When the using statement disposes the returned object, it’ll close out the tag.


@using (Html.BeginForm()) {
// Form Fields go here
}

Additional Information

Full Code

About the Author Dustin Ewers

follow me on:

Leave a Comment: