IF..ELSE statements in a view are untrusted in ASP.NET MVC?

I know that you want to keep the logic out of your views. I can bring most loops with DisplayFor / EditorFor and pass IEnumerables to the view.

What about IF instructions? should they be completely avoided in looks? used sparingly? as a last resort?

Suppose you want to show a hidden element based on a user role ... How could you do this without an IF statement ... perhaps a completely separate view?

Just trying to get an idea of ​​best practices.

Thanks!

+6
source share
7 answers

Be consistent and don't forget about the purpose of the presentation - to create your own HTML. To do this, you will certainly need some if constructs here or there. I think that some people suggest you stick to some kind of cake in the sky, ultra-insignificant purism here due to a useful, functional, well-defined code.

+13
source

There is nothing wrong with using if in your views unless you insert backend logic into them.

+9
source

Rob Conery has a rule of thumb that states "if there is IF, make an assistant . " Personally, I would say "use sparingly." I avoid this as much as possible because it complicates the unit test task.

In a situation where you want to hide elements based on user roles: for simple scenarios, I would probably put the check directly in the view. However, I try, however, to make them more concise and verified. Therefore, instead of:

 @if (HttpContext.Current.User.IsInRole("admin") { // Show admin stuff } 

I would do something like:

 @if (Model.UserIsAdmin) { // Show admin stuff } 

On the other hand, if these types of checks began to pop up across all your representations, I would probably first create elements conditionally in the viewmodel area, and then just show what was built. Hope this helps.

+3
source

Basically, each view should show what is passed to the ViewModel. If the ViewModel is not enough, then I would look for a way to improve the creation of the ViewModel itself, and not the presentation logic.

All CAN conventions can be evaluated when creating a ViewModel.

Of course, it all depends on how much the user logic in the view fulfills your project organization.

0
source

If / else can be used sparingly, in my opinion, but for the example you mentioned, hide the element based on the role - if the check should not be in the view. Record extensions and helpers where necessary.

0
source

I think it’s better to avoid it if in the view you should avoid the logic of the business (model) or application (controller) in the view in your example, you can create a separate Partial View for display, which is believed to depend on the role of the user, and in Controller - logic for the view you need to show

0
source

I would suggest hiding the "if" element in the view, but in the code you must disable the function (method) that is activated by the hidden element.

0
source

Source: https://habr.com/ru/post/886467/


All Articles