Created
June 5, 2017 16:50
-
-
Save jeremysimmons/4c512c1ba6bb87f48f2e33203d93c7e1 to your computer and use it in GitHub Desktop.
Conditional attribute rendering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@using System.Collections.Generic | |
@{ | |
ViewData["Title"] = "Home Page"; | |
var Colors = new List<string> | |
{ | |
"thunderbird", | |
"mandarin", | |
"saffron", | |
"shamrock", | |
"aqua", | |
"royal", | |
"lavender" | |
}; | |
var selectedColor = "aqua"; | |
} | |
@foreach (var color in Colors) | |
{ | |
@color <input type="radio" id="@color" value="@color" checked="@(color == selectedColor)" /><br/> | |
} | |
output: | |
thunderbird <input id="thunderbird" type="radio" value="thunderbird"><br> | |
mandarin <input id="mandarin" type="radio" value="mandarin"><br> | |
saffron <input id="saffron" type="radio" value="saffron"><br> | |
shamrock <input id="shamrock" type="radio" value="shamrock"><br> | |
aqua <input id="aqua" type="radio" checked="checked" value="aqua"><br> | |
royal <input id="royal" type="radio" value="royal"><br> | |
https://weblogs.asp.net/jongalloway/asp-net-4-beta-released | |
Conditional attribute rendering | |
If you have an attribute that might be null, in the past you've needed to do a null check to avoid writing out an empty attribute, like this: | |
<div @{if (myClass != null) { <text>class="@myClass"</text> } }>Content</div> | |
Now Razor is able to handle that automatically, so you can just write out the attribute. If it's null, the attribute isn't written: | |
<div class="@myClass">Content</div> | |
So if @myClass is null, the output is just this: | |
<div>Content</div> | |
Again, this is a Razor feature, so it's shared with ASP.NET Web Pages 2. | |
lavender <input id="lavender" type="radio" value="lavender"><br> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment