Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor template variable scope

Are variables I define in a shared layout _Layout.cshtml within scope of a View page?

_Layout.cshtml varibles:

@{
    ViewBag.url = "http://www.website.com/site/";
}

Index.cshtml:

<a class="continue" href="@ViewBag.url/our-vision/">Continue</a>

This outputs: /our-vision/

like image 353
CharliePrynn Avatar asked Aug 13 '26 04:08

CharliePrynn


1 Answers

You could try answer from this question: How do I set ViewBag properties on _ViewStart.cshtml?

Set (Note: code is for _ViewStart, not for _Layout)

@{
    PageData["message"] = "Hello";
}

Get

<h2>@PageData["message"]</h2>

OR

Create more interesting solution: How to set ViewBag properties for all Views without using a base class for Controllers?

like image 163
webdeveloper Avatar answered Aug 16 '26 15:08

webdeveloper