Saturday, December 10, 2022

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

Issue

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="vote-up@{puzzle.UserVote == VoteType.Up ? "-selected" : ""}">Vote Up</span>

However there's two problems here:

  1. vote-up@{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?


Solution

This should work:

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


Answered By - CD..
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.