Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor If/Else conditional operator syntax [duplicate]

Not having much luck, I have the following if/else statement in Razor which works perfectly

<small>   @if(deletedView){      @:Deleted   }    else {      @:Created   } by </small>  

I am trying to do something like this:

<small>   @(deletedView) ? @:Deleted : @:Created by </small> 

But that fails miserably. What is the proper syntax?

like image 345
B Z Avatar asked Jan 05 '11 18:01

B Z


People also ask

How do you write if condition in razor view?

The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.

What is Razor syntax?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.

What is Razor in Visual studio?

What is Razor? Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. Server-based code can create dynamic web content on the fly, while a web page is written to the browser.

Is Razor a language?

The Razor syntax is based on the C# programming language, and that's the language that's used most often with ASP.NET Web Pages. However, the Razor syntax also supports the Visual Basic language, and everything you see you can also do in Visual Basic.


1 Answers

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by") 

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

like image 164
Andrew Stanton-Nurse Avatar answered Sep 24 '22 21:09

Andrew Stanton-Nurse