How can I write this if
statement
@if (camera.IsInStock)
{
<span class="text-success" style="float:right">IN STOCK</span>
}
else
{
<span class="text-danger" style="float:right">OUT OF STOCK</span>
}
in expression like this:
@(camera.IsInStock ? "<span style='float:right' class='success'>IN STOCK</span>" : "<span style='float:right' class='danger'>OUT OF STOCK</span>")
The expression I provided doesn't work. Thanks
When you are trying to render the HTML markup inside a ternary expression, you should use Html.Raw
method so that it will not get html encoded by razor.
@(camera.IsInStock ?
Html.Raw("<span style='float:right' class='text-success'>IN STOCK</span>")
: Html.Raw("<span style='float:right' class='text-danger'>OUT OF STOCK</span>"))
I personally prefer your first approach as i feel that is more readable. you may also consider creating helper methods which takes the IsInStock
flag and return the css class needed and the text needed or even your entire span markup.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.