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?
42.
Just kidding :-)
There's no set answer to this, though a good separation of concerns is a generally accepted best practice. The debate around this can be pretty endless, and knowing the right way to do it for your particular project comes with experience I think and being able to notice "code smell" or things that don't feel right.
if the logic pertains to the format of the view, and does not result in changes to entities or data, then I think it is OK in the view.
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.
Here's another way to think about it. Presentation logic goes in the view. Business processing logic goes in the controller, and data validation goes in the model. But what goes where should ultimately be guidance and not religion:)
As long as the logic in the view is for the presentation (you could put it in the code behind file if you don't like it in the markup file) then it is ok. In your example the code / logic is for selecting a certain view part which is ok. The presentation is allowed to have logic it doesn't need to be simply HTML.