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.
Here is a little util I wrote to do this. It is a little more generic so you can use it for any tag and with any attributes. It is setup as an extension method on HtmlHelper so you can use it right from within Razor as well as from within code.
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 implementsIDisposable
.The
IDisposable
interface defines a single method calledDispose
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 withIDisposable
is natural.You'll want to implement a
Section
class 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.