Asp.net-mvc – How much logic is allowed in ASP.NET MVC views

asp.net-mvcviews

In looking at samples of ASP.NET MVC sites, I'm seeing quite a bit of examples with embedded logic in the views, e.g.:

<% if (customerIsAllowed)
   { %>

   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>

<% }  else {%>

   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>

<% } %>

Although this seems wrong to me since it is the kind of thing we were trying to get away from in ASP 3.0, I have even heard in some podcasts how "a little bit of logic in view is ok" since the rest of the MVC framework is taking care of the structure that we didn't have in ASP 3.0.

Are there any MVC conventions specifying what kind and how much logic is allowed in views?

Best Answer

It depends on the reason for the logic. If the logic is choosing an alternate presentation based on some property passed to it by the controller, it is probably ok. This allows you some view reuse. Instead of having to recreate (and repeat) an entire view for each custom privilege, you can pass in some data that allows the view to be customized based on this privilege.

I think of this as a pragmatic balance between an idealized MVC and strict enforcement of DRY (don't repeat yourself). In some situations it is wiser to violate one or the other if you can't attain both easily. In the case where clearly the model and the basic view is the same, putting a little logic in the view to keep your views DRY is reasonable.