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

asp.netasp.net Mvcasp.net Mvc-3SyntaxRazor

asp.net Problem Overview


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?

asp.net Solutions


Solution 1 - asp.net

This should work:

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

Solution 2 - asp.net

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

Solution 3 - asp.net

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

Solution 4 - asp.net

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMicahView Question on Stackoverflow
Solution 1 - asp.netCD..View Answer on Stackoverflow
Solution 2 - asp.netDaniel SantosView Answer on Stackoverflow
Solution 3 - asp.netJPCView Answer on Stackoverflow
Solution 4 - asp.netDamian VogelView Answer on Stackoverflow