When should I use the HtmlHelper extension methods?

I increasingly find situations where my ASP.NET MVC view requires some logic to execute the layout. These routines have no place either in my model or in my controller. I have 3 options:

  • Enter many lines <%%> inline in the view.
  • Write less than <%%> regarding partial representations.
  • Enter the HtmlHelper extension method.

This is the last option that bothers me. Can this be done if the logic is specific to only one representation? The extension will be “visible” to the Html object of any other view, and it will never be needed.

Any suggestions?

+3
source share
3 answers

I personally prefer option 3 ("Write the HtmlHelper Extension method"), because those code bodies can be easily tested.

I really want extension methods to be placed on inner or nested classes, because you're right, you will start polluting your namespaces with tons of extension methods that are used in only one view.

I would recommend sequestering these HtmlHelper extension methods in static classes in the user namespace for each view that you manually reference in the view to limit the number of extension methods available in your project.

+5
source

, , , , . , , . , / , - .

( ), . , .

+1

, ?

. ...

"" Html .

No. It depends on how you register the extension method for the view. This only happens if you add a namespace to the namespaces section of web.config.

If you want to use the extension method on one view, just import its namespace into one view:

<%@ Import Namespace="NamespaceOf.Your.ExtensionMethods.ForThisViewOnly"%>
0
source

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


All Articles