Ricardo Polo Jaramillo
Ricardo Polo Jaramillo

Reputation: 12318

Difference between ( ) (parenthesis) and { } (curly brackets) in Razor

What is the difference between them both. I thought they were the same but today I realized that they are not.

Why this is correct

@(Model.WillAttend == true ? 
    "This will be an exciting party with you" : 
    "So sorry. You'll lose the beeer")

and this is not:

@{Model.WillAttend == true ? 
    "This will be an exciting party with you" : 
    "So sorry. You'll lose the beeer"}

Upvotes: 29

Views: 9822

Answers (3)

Betty
Betty

Reputation: 9189

If you're familiar with WebForms, it's very similar to the difference between <%= %> (or <%: %>) and <% %>. The former is evaluated then outputted to the page, the latter is a block of code that can do whatever it needs (but isn't written to the page).

Upvotes: 6

Levin
Levin

Reputation: 2015

To the question: "why is the second one not valid?", in addition to what Betty and Justin say, the issues specific to what you show: inside curly braces you need your code to follow the normal syntax of c#, so you can't have just a loose "a==b?c:d", without assigning the result to something. And you need a semicolon. So you could say

@{string message = Model.WillAttend == true ? 
     "This will be an exciting party with you" : 
     "So sorry. You'll lose the beeer";}

Upvotes: 8

Justin Pihony
Justin Pihony

Reputation: 67115

The paren is just an explicit expression, and you will notice that you do not need a semi-colon. The brackets are a code block, to be used just like any other piece of code. Expressions have their output submitted as part of the HTML, whereas code blocks do not.

Phil Haack actually wrote a good primer on some Razor syntax

Upvotes: 29

Related Questions