I want to create a helper that i can add content between the brackets just like Helper.BeginForm() does. I wouldnt mind create a Begin, End for my helper but it’s pretty simple and easy to do it that way.
basically what i am trying to do is wrapping content between these tags so they are rendered already formatted
something like
@using Html.Section("full", "The Title")
{
This is the content for this section
<p>More content</p>
@Html.TextFor("text","label")
etc etc etc
}
the parameters “full” is the css id for that div and “the title” is the title of the section.
Is there a better way to achieve this other than doing what i am trying to do?
thanks in advance for any help.
It’s totally possible. The way this is done in MVC with things like
Helper.BeginFormis that the function must return an object that implementsIDisposable.The
IDisposableinterface defines a single method calledDisposewhich is called just before the object is garbage-collected.In C#, the
usingkeyword is helpful to restrict the scope of an object, and to garbage-collect it as soon as it leaves scope. So, using it withIDisposableis natural.You’ll want to implement a
Sectionclass which implementsIDisposable. 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:Now that the type is available, you can extend the HtmlHelper.