Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line If statement with Razor and .NET

Razor doesn't seem to like my one line If statements... Normally in VB.NET, I can write a one line If statement like so:

If True Then Dim x As Integer

However, when I do the same with Razor in a .vbhtml file like this...

@If True Then Dim x As Integer

I get the error

The "If" block was not terminated. All "If" statements must be terminated with a matching "End If".

What gives? Why won't Razor take this? I realize that a simple solution is to just use a code block like

@code
    If True Then Dim x As Integer
End Code

But thats not what I'm looking for. I'm curious why Razor can't recognize a VB.Net one line If statement using just @If.... Any ideas?

like image 840
ElliotSchmelliot Avatar asked Aug 20 '13 18:08

ElliotSchmelliot


People also ask

Is Cshtml a Razor?

All Razor files end with . cshtml. Most Razor files are intended to be browsable and contain a mixture of client-side and server-side code, which, when processed, results in HTML being sent to the browser. These pages are usually referred to as "content pages".

How can you comment using Razor syntax?

Razor uses the syntax "@* .. *@" for the comment block but in a C# code block we can also use "/* */" or "//". HTML comments are the same, "<!

What is @: In Cshtml?

CSHTML files use the @ symbol and Razor reserved directives to transition from HTML markup to C# code. Most CSHTML files are created in Microsoft Visual Studio. Visual Studio provides syntax highlighting and Intellisense code suggestions that help developers create CSHTML files.


2 Answers

In VB.Net you do a inline If Statement like this:

@(If(boolCondition, "truePart", "falsePart"))
like image 132
jweaver Avatar answered Sep 25 '22 14:09

jweaver


Same problem with C#, As explained here :

Razor uses code syntax to infer indent: Razor Parser infers code ending by reading the opening and the closing characters or HTML elements. In consequence, the use of openings “{“ and closings “}” is mandatory, even for single line instructions

You do the wright thing

@code
    If True Then Dim x As Integer
End Code

You can do it like that but it's not you like (inline)

@If (True) Then
    Dim x As Integer
End If
like image 36
Joan Caron Avatar answered Sep 23 '22 14:09

Joan Caron