user274364
user274364

Reputation: 1857

Creating Html Helper Method - MVC Framework

I am learning MVC from Stephen Walther tutorials on MSDN website. He suggests that we can create Html Helper method.

Say Example

using System;
namespace MvcApplication1.Helpers
{
          public class LabelHelper
          {
               public static string Label(string target, string text)
               {
                    return String.Format("<label for='{0}'>{1}</label>",
                    target, text);
               }
          }
}

My Question under which folder do i need to create these class?

View folder or controller folder? or can i place it in App_Code folder?

Upvotes: 2

Views: 2132

Answers (4)

Brian Mains
Brian Mains

Reputation: 50728

You could put in the Models folder, or App_Code (not sure what kinds of support is in MVC for that); it would be best to have in a separate library. Also, html helper extensions are extension methods that must start with the this HtmlHelper html parameter like:

public static class LabelHelper 
         { 
               public static string Label(this HtmlHelper html, string target, string text) 
               { 
                    return String.Format("<label for='{0}'>{1}</label>", 
                    target, text); 
               } 
          } 

EDIT: You can reference this within the namespace by adding it to the:

<pages>
   <namespaces>

Element within the configuration file too, that way you define the namespace once, and it's referenced everywhere.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

I would create a subfolder Extensions in which define helper methods:

namespace SomeNamespace
{
    public static class HtmlHelperExtensions
    {
        public static string MyLabel(this HtmlHelper htmlHelper, string target, string text)
        {
            var builder = new TagBuilder("label");
            builder.Attributes.Add("for", target);
            builder.SetInnerText(text);
            return builder.ToString();
        }
    }
}

In your view you need to reference the namespace and use the extension method:

<%@ Import Namespace="SomeNamespace" %>

<%= Html.MyLabel("abc", "some text") %>

Upvotes: 2

Mattias Jakobsson
Mattias Jakobsson

Reputation: 8237

You can place it wherever you like. The important thing is that it make sense to you (and everyone working on the project). Personally I keep my helpers at this path: /App/Extensions/.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191058

Place it in the app code. However, ASP.NET MVC 2 already has the Label functionality.

Upvotes: 0

Related Questions