Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand if else with razor

Im using this in my view and want it to display only "Yes" or "No" but its displaying False?"yes":"No"

@myPosts.Contains(item.ID)?"Yes":"No"

Whats wrong here?

like image 412
raklos Avatar asked Jan 02 '11 18:01

raklos


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 in MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

How check MVC model is empty?

If you are trying to check if model is empty which is not a list and may contain single record or none then I normally use @if(Model == null) .

What are razor websites?

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.


2 Answers

You need parentheses to use an expression:

@(myPosts.Contains(item.ID)?"Yes":"No") 
like image 179
Guffa Avatar answered Oct 25 '22 19:10

Guffa


You can even nest shorthand if inside of another shorthand if!

@(myPosts != null ? (myPosts.Contains(item.ID) ? "Yes" : "No") : "Null")
like image 28
Eric K Avatar answered Oct 25 '22 20:10

Eric K