Creating Html Helper Method - MVC Framework

I am learning MVC from Stephen Walther's tutorials on the MSDN website. He suggests creating an Html Helper method.

Say an 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 is, in which folder do I need to create this class?

View folder or controller folder? Or can I put it in the App_Code folder?

+2
source share
4 answers

I would create an Extensions subfolder that defines 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
source

You can place it wherever you want. The important thing is that this makes sense to you (and everyone who works on the project). Personally, I keep my helpers along the way: /App/Extensions/ .

+1
source

Put it in the application code. However, ASP.NET MVC 2 already has Label functionality.

0
source

You can put it in the Models or App_Code folder (not sure what support in MVC is for this); it would be better to have in a separate library. In addition, html helper extensions are extension methods that must begin with this htmlHelper html parameter, for example:

 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 in the namespace by adding it to:

 <pages> <namespaces> 

An element in the configuration file too, so you define the namespace once and refer everywhere.

0
source

Source: https://habr.com/ru/post/987122/


All Articles