Razor is great when it comes to conditional HTML output, or outputting HTML in a for-loop,
but when it comes to conditional code within the element itself things are a bit more tricky.
For example , the following code does not compile because you cannot add C# control blocks inside the <
and >
of an element.
The next approach we might attempt is to write a method that returns a string and call that inside the <
and >
characters.
But this doesn't work either. The preceding example would output the following HTML.
Razor will only execute C# code in the following places:
- Inside an element's content area, for example
<span>@GetSomeHtml()</span>
. - When determining a value to assign into an element's attribute, for example
<img src=@GetTheImageForTheUrl() />
. - Within the
@code
section.
The technique we need to employ to generate one or more attributes + values for a HTML element is called "Attribute splatting".
Attribute splatting involves assigning a Dictionary<string, object>
to an attribute with the special name @attributes
.
The preceding code will output a <div>
with 5 attributes.
Special cases
Some HTML attributes, such as readonly
and disabled
require no values - their mere presence on the element is sufficient
for them to be effective.
In fact, even apply a value such as false
will still activate them. The following <input>
element will be both
readonly
and disabled
.
In razor views the rule is slightly different.
If we output readonly=@IsReadOnly
or disabled=@IsDisabled
- whenever the value being assigned is false razor will not
output the attribute at all;
when the value being assigned is true razor will output the element without assigning a value.
<input readonly=@true disabled=@false/>
will result in razor generated HTML that does not include the disabled
attribute
at all.