views:

262

answers:

3

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 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?

+4  A: 

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.

cfeduke
+1  A: 

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.

tvanfosson
A: 

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"%>
Dmytrii Nagirniak
But that will not work with HtmlHelper as all the extension methods must be part of the same namespace.
Chris Arnold
It will. Just import the namespaces you want to use on a single page.
Dmytrii Nagirniak
Not if I add extension methods to HtmlHelper though. The all have to exist in the same namespace as HtmlHelper in order to work.
Chris Arnold
"have to exist in the same namespace as HtmlHelper" - this is not true. You can import YOUR extensions from YOUR namespace and they will work with HtmlHelper.
Dmytrii Nagirniak