Applying Conditional Attributes in ASP.NET MVC Views

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:

  1. <!-- Using an if-statement -->   
  2. <div @{if (Model.YourProperty != null{<text>class="@Model.YourProperty"</text>}}>   
  3. Your Content  
  4. </div>   
Or:
  1. <!-- Using a ternary operator -->   
  2. <div class="@(Model.YourProperty != null ? Model.YourProperty : "")">   
  3. Your Content  
  4. </div>   
Using Conditional Attributes in MVC4

More recent versions of ASP.NET MVC (4 and beyond) support the following syntax:
  1. <!-- Using a Conditional Attribute -->   
  2. <div class="@Model.YourProperty">   
  3. Your Content  
  4. </div>   
This may appear straight-forward, however the Razor View engine does a bit of work behind the scenes and handles some of the previously seen logic automatically. So if the property or value that you are checking within the attribute is null, the attribute will not even be written at all. This only applies to null values, an empty string would still render the corresponding attribute).

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:
  1. <div class>Your Content</div>   
However, the newer versions will detect that the property is null and completely ignore writing the attribute at all:
  1. <div>Your Content</div>   
The examples above obviously only demonstrate this functionality with the class attribute, however it should be noted that it will work for any attribute that might be applied the same way. Custom HTML5 data attributes or checked attributes would be excellent choices to handle this way as well.

 


Similar Articles