开发者

When should I use HtmlHelper Extension Methods?

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

  1. Write lots of <% %> inline in the view.
  2. Write less <% %> in a number of partial views.
  3. Write an HtmlHelper Extension method.

It is the last option that confuses me. Is it OK to do this if the开发者_JAVA技巧 logic is specific to only that one view? The extension would be 'visible' to the Html object of every other view, and it will never be needed.

Any suggestions?


I personally prefer option 3 ("Write an HtmlHelper Extension method") because those bodies of code lend themselves to be easily unit testable.

I really do wish extension methods could be placed on internal or nested classes because you are right, you will begin to pollute your namespaces with tons of extension methods which are only used in one View.

I'd recommend sequestering these HtmlHelper extension methods in static classes in a custom namespace per View that you manually reference in the View so as to limit the number of extension methods available throughout your project.


I would, generally, limit both partial views and extension methods to reusable components, but am not pedantic about it. If you feel that either one improves the readability of your code, then go ahead and use them. You might want to consider a separate namespace/helper class for helper methods that are only used by one set of views -- sort of like segregating your partials per controller.

You might also want to consider using more whitespace (even though it's the silent killer) to improve readability. I've implemented output compression in my base controller to limit the impact of whitespace on download time.


Is it OK to do this if the logic is specific to only that one view?

Yes. Read on...

The extension would be 'visible' to the Html object of every other view, and it will never be needed.

No true. It depende how you register the extension method for the view. This is only the case if you add the namespace to the web.config namespaces section.

If you want to use the extension method on a single view just import its namespace to the single view:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜