Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten this if statement in Razor to one line

Tags:

Can i shorten this to one line? I have tried various ways but can't quite get it right.

@if(SiteMap.CurrentNode.Title == "Contact") {     @:<div class="contact"> } 
like image 551
Todd Avatar asked Dec 07 '11 21:12

Todd


People also ask

How do you write an if statement in a Razor?

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 the syntax of Razor?

The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension. Razor is also found in Razor component files ( .

What are Razor expressions used for?

Razor Expression Encoding Razor provides expression encoding to avoid malicious code and security risks. In case, if user enters a malicious script as input, razor engine encode the script and render as HTML output.

What is Razor template?

Razor is a templating engine that was introduced with ASP.NET MVC, originally to run on the server and generate HTML to be served to web browsers. The Razor templating engine extends standard HTML syntax with C# so that you can express the layout and incorporate CSS stylesheets and JavaScript easily.


2 Answers

There might be an even simpler solution but this should work:

@Html.Raw((SiteMap.CurrentNode.Title == "Contact") ? "<div class='contact'>" : "") 
like image 116
xbrady Avatar answered Sep 16 '22 23:09

xbrady


The shortest possible way to do is like:

@(SiteMap.CurrentNode.Title == "Contact" ? "<div class='contact'>" : "") 

or

@(SiteMap.CurrentNode.Title == "Contact" ? @"<div class=""contact"">" : "") 

or even shorter if you don't repeat your html code

<div class="@(SiteMap.CurrentNode.Title == "Contact" ? "contact" : "")"> 
like image 28
HasanG Avatar answered Sep 17 '22 23:09

HasanG