Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are IF..ELSE statements in a View frowned upon in ASP.NET MVC?

I know that you want to keep logic out of your views. I can elimate most loops by using DisplayFor/EditorFor and passing IEnumerables to the view.

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

Say you wanted to show hide an element based on a User role...How would u go about doing this without an IF statement...a completely seperate view perhaps?

Just trying to get an idea of best practices.

Thanks!

like image 696
stephen776 Avatar asked Apr 22 '11 11:04

stephen776


2 Answers

Be consistent, and keep in mind the purpose of the view - to produce your HTML. Toward that end, certainly you will need some if constructs here or there. I think some people are suggesting you stick to some pie-in-the-sky, ultra-nitpicky purism here at the expense of usable, functional, well-defined code.

like image 180
Andrew Barber Avatar answered Oct 16 '22 02:10

Andrew Barber


There is nothing wrong with using ifs in your views, as long as you don't end up putting backend logic in them.

like image 29
SLaks Avatar answered Oct 16 '22 01:10

SLaks