views:

82

answers:

4

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?

A: 

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

Daniel A. White
+1  A: 

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/.

Mattias Jakobsson
A: 

Hey,

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.

Brian
Correct. If it doesn't start with this HtmlHelper html, then it is not the extension and you have to call it like LabelHelper.Label instead of Html.Label
šljaker
A: 

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") %>
Darin Dimitrov