I need a quick sanity check. I’m trying to design my views such that they are clean, concise, and as free from any sort of conditional logic as possible. However, I’m having a hard time ridding them of all conditional statements. I’m wondering if having some conditional statements in views is unavoidable?
For example:
@if (Model.UserCanEdit)
{
<button type="button" id="Edit">Edit</button>
}
There are not many options if you have a view that has several elements that can change or be shown/hidden depending on various conditions.
So what guidelines should I follow regarding where to draw the line on allowing conditional logic in your views? What are some ways to reduce conditional logic in my views that I may not be thinking of?
Thanks in advance.
I wouldn’t say that it is all bad using conditionals in Views – after all the main purpose of a view is actually displaying data from your Model. (And some times conditional statements are required to display the data.)
Possible Alternatives:
Custom HTML Helpers:
If you aren’t crazy about using conditionals – you can look into using Helpers to clean up things a bit. For more information on that check out Creating Custom HTML Helpers.
Additional Views / Partial Views:
Also, as many will point out – using conditionals to make a single view function as multiple views should is not the best way to tackle that issue.