Peter
Peter

Reputation: 9123

Overriding variables in Razor views

I'm fairly new to the whole AspNetCore MVC scene and I've stumbled into some trouble while writing my html.

I've got the followingL

_layout.cshtml

@{
    bool showTitle = true;
}

....

if (showTitle)
{
    ....
}

Page.cshtml

@{
    showTitle = false;
}

To clairy

I would like to have the title of the page showing by default and have the option to hide it from particular view files. However, I'm not able to overwrite the showTitle variable because it is unknown in the view files.

Upvotes: 1

Views: 371

Answers (2)

Roar S.
Roar S.

Reputation: 11099

I usually solve this by using the inverse logic in _layout.cshtml

@if (ViewData["hideTitle"] != null)
{
    ... render something
}
else
{
    ... default behaviour, render something else
}

Often used for overriding page titles like this:

_layout.cshtml

@if (ViewData["Title"] != null)
{
    <title>@ViewData["Title"] | My Fantastic Website</title>
}
else
{
    <title>My Company | My Fantastic Website</title>
}

And you override page title in concrete views like this:

@{
    ViewData["Title"] = "About Us";
}

Views that don't define ViewData["Title"], will get default title <title>My Company | My Fantastic Website</title>.

Upvotes: 2

Stanislav Stoyanov
Stanislav Stoyanov

Reputation: 2120

How about putting the variable in the ViewBag and set it in the Controller

_layout.cshtml

if (ViewBag.ShowTitle == null || ViewBag.ShowTitle == true)
{
    ...
}

Controller

{
     ViewBag.ShowTitle = false;
     return View();
}

Upvotes: 2

Related Questions