Creating Html Helper Method - MVC Framework

夙愿已清 提交于 2019-12-01 08:56:34

问题


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?


回答1:


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



回答2:


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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2432551/creating-html-helper-method-mvc-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!