Reputation:
From server side, I defined a new boolean value and set it into <input>
tag, but browser couldn't detect it.
@{ var isAuthor = false; }
<input type="hidden" value="@isAuthor" />
After compiling, the result was: <input type="hidden"></input>
But, when I tried to convert isAuthor
to a string
, it should work:
@{ var isAuthor = false; }
<input type="hidden" value="@isAuthor.ToString()" />
Result: <input type="hidden" value="false"></input>
Why? Did I miss something?
Upvotes: 18
Views: 11670
Reputation: 24901
This is a Razor view engine feature called conditional attributes. The idea is to simplify the scenario, where you want or don't want to render the attribute based on the value. Previously you had to write if
statement or use ternary operator to handle that, but with conditional attributes it is all much simplified.
With conditional attributes, if the value of an attribute is null
or false
, then the attribute is not rendered. If you want the value to be false
you need to cast it to string, just like you did in the question.
You can read a great introduction to conditional Razor attributes in this blog article
Upvotes: 19