How to use ? : if statements with Razor and inline code blocks

I’m updating my old .aspx views with the new Razore view engine. I have a bunch of places where I have code like this:

<span class="vote-up<%= puzzle.UserVote == VoteType.Up ? "-selected" : "" %>">Vote Up</span>

Ideally I’d like to do this:

<span class="<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8aeb7acbdf5ada898">[email protected]</a>{puzzle.UserVote == VoteType.Up ? "-selected" : ""}">Vote Up</span>

However there’s two problems here:

  1. [email protected]{puzzle.UserVote …. is not treating the @ symbol as a start of a code block
  2. @puzzle.UserVote == VoteType.Up looks at the first part @puzzle.UserVote as if it’s supposed to render the value of the variable.

Anyone know how to address these issues?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This should work:

<span class="<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e38213a2b633b3e0e">[email protected]</a>(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>

Method 2

@( condition ? "true" : "false" )

Method 3

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

Method 4

In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:

 @(String.IsNullOrEmpty(Model.MaidenName) ? "&nbsp;" : Model.MaidenName)

This would print me “&nbsp;” in my page, respectively generate the source &amp;nbsp;. Now there is a function Html.Raw("&nbsp;") which is supposed to let you write source code, except in this constellation it throws a compiler error:

Compiler Error Message: CS0173: Type of conditional expression cannot
be determined because there is no implicit conversion between
‘System.Web.IHtmlString’ and ‘string’

So I ended up writing a statement like the following, which is less nice but works even in my case:

@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw("&nbsp;") } else { @Model.MaidenName }

Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x