Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rolling my own @Html.BeginfBrm()

I am writing a custom validation set that will display all missing elements on a div. I'd like to be able to use a custom @Html.BeginForm() method that will write out that div but I'm really not sure where to even begin as this nut is a little tougher to crack than just a html extension that writes out a Tag or String (the form encapsulates data/controls and is closed by } at the end).

I looked at the metadata version of the built in BeginForm() method and it wasn't much help to me. Essentially, I just want to extend that method if possible and have it write out a MvcHtmlString of a div that will be show/hidden from JavaScript.

ultimately where I'm struggling is figuring out how to write this custom helper that has the beginning and ending component to it.

@using(Html.BeginForm())
{
...

}

I'd want to be able to do something like this:

@using(Html.VBeginForm())
{
...

}

and have that render my extra html

EDIT: adding code from suggestion below

public class VBeginForm : IDisposable
{
    private readonly HtmlHelper _helper;
    public VBeginForm(HtmlHelper htmlHelper, string areaName)
    {
        _helper = htmlHelper;
        var container = new TagBuilder("form");
        container.GenerateId(areaName);
        var writer = _helper.ViewContext.Writer;
        writer.Write(container.ToString(TagRenderMode.StartTag));
    }

    public void Dispose()
    {
        _helper.ViewContext.Writer.Write("</form>");
    }
}
like image 209
Christopher Johnson Avatar asked Jun 17 '11 14:06

Christopher Johnson


1 Answers

You need to write an extension method for the HtmlHelper class that prints to helper.ViewContext.Writer.

The method should return an IDisposable that prints the closing tag in its Dispose method.

like image 80
SLaks Avatar answered Oct 07 '22 22:10

SLaks