Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating MVC3 Razor Helper like Helper.BeginForm()

Tags:

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.

like image 304
Pepito Fernandez Avatar asked Aug 25 '11 19:08

Pepito Fernandez


People also ask

How to create a custom HTML Helper?

There are two ways in MVC to create custom Html helpers as below. We can create our own HTML helper by writing extension method for HTML helper class. These helpers are available to Helper property of class and you can use then just like inbuilt helpers. Add new class in MVC application and give it meaningful name.

What is helper in ASP NET MVC?

HtmlHelper is a class which is introduced in MVC 2. It is used to create HTML controls programmatically. It provides built-in methods to generate controls on the view page. In this topic we have tabled constructors, properties and methods of this class.


1 Answers

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); } 
like image 118
Wyatt Avatar answered Oct 02 '22 14:10

Wyatt