Typo Johnson
Typo Johnson

Reputation: 6044

In a Razor view how can I insert the page title without a <?

In my ASP.NET MVC 3 Razor layout view I want my page title to always be "My Website" and if ViewBag.Title is set I want to append that to the title, using a hyphen as a separator. I want this code to be on a single line

This code fails :

<title>My Website @if( string.IsNullOrEmpty( ViewBag.Title) == false){ - @ViewBag.Title}</title>

With

The if block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

Presumably because @: assumes that the rest of the line is markup. I can't use a span tag to help Razor because the browser title becomes "My Website - span Home span".

Yes I can spread this over two or three lines, but I don't want to. This works but is it my only option with Razor ?

<title>My Website @if( string.IsNullOrEmpty( ViewBag.Title) == false){ @: - @ViewBag.Title
}</title>

Upvotes: 2

Views: 7947

Answers (2)

archil
archil

Reputation: 39501

i think you need razor explicit text markup

 <title>My Website @if( string.IsNullOrEmpty( ViewBag.Title) == false){ <text>-</text> @ViewBag.Title}</title>

Upvotes: 4

SLaks
SLaks

Reputation: 888187

You need to use the <text> pseudo-tag.

<title>My Website @if(!string.IsNullOrEmpty(ViewBag.Title)) { <text>- @ViewBag.Title</text> }</title>

Upvotes: 5

Related Questions