Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much logic is allowed in ASP.NET MVC views?

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?

like image 383
Edward Tanguay Avatar asked Jan 14 '09 14:01

Edward Tanguay


People also ask

How many views does the model can have in MVC?

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible.

Can we have multiple views for single controller?

Yes You can use multiple View in one Controller.

Where is the logic in MVC?

A1: Business Logic goes to Model part in MVC . Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do. A2: A Business Rule is part of Business Logic .

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.


2 Answers

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.

like image 194
tvanfosson Avatar answered Oct 07 '22 14:10

tvanfosson


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.

like image 40
Matthew Avatar answered Oct 07 '22 16:10

Matthew