If you have attempted to handle any kind of conditional logic within MVC Views before, you know that the process can often be tricky to get everything to work just right. A feature is present in newer versions of ASP.NET MVC provides support for handling conditional attributes, which might make those large sets of if-statements and other logic in your Views a thing of the past.
Ugly Ifs and Ternary Statements
Previously, if you wanted to add a conditional attribute to a particular element, you would need to use a conditional statement (e.g. an if-statement, switch statement or an inline if-statement using the ternary operator).
If you had needed to check a specific property of your model and apply a class accordingly, you might have some code that resembles the following through an if-statement which:
- <!-- Using an if-statement -->
- <div @{if (Model.YourProperty != null{<text>class="@Model.YourProperty"</text>}}>
- Your Content
- </div>
- <!-- Using a ternary operator -->
- <div class="@(Model.YourProperty != null ? Model.YourProperty : "")">
- Your Content
- </div>
More recent versions of ASP.NET MVC (4 and beyond) support the following syntax:
- <!-- Using a Conditional Attribute -->
- <div class="@Model.YourProperty">
- Your Content
- </div>
Using the syntax above, let’s say we pass a model will the YourClassToApply property as null, previous versions of MVC would render the following:
- <div class>Your Content</div>
- <div>Your Content</div>

Raja TPosted Nov 14, 2015, 12:34 PM
Nice, Thanks for sharing...
Gowtham RajamanickamPosted Nov 14, 2015, 12:48 AM
nice one
Harshad PansuriyaPosted Nov 13, 2015, 10:58 PM
Nice one
Ramesh MaruthiPosted Nov 13, 2015, 4:46 PM
Simple and sweet, thank you Rion Williams !!
Banketeshvar NarayanPosted Nov 13, 2015, 10:37 AM
nice share