开发者

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 开发者_如何学GoLabelHelper
          {
               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?


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜