Global Variables in Razor View Engine
Is there a way for me to use a functionality similar to what are called Global Variables in the Spark View Engine, but for Razor.
The point of it all li开发者_开发百科s to be able to define a variable in one section for the title and then being able to set or change the value of that variable later on in another section.
In Spark you would create the variable in a section kind of like this (incomplete code for example purposes):
<html>
<head>
<global type='string' Title='"Site Name"'/>
<title>${Title}</title>
</head>
<body>
<div><use content="view"/></div>
</body>
</html>
And then you could set it in a different view or section or whatever:
<set Title='product.Name + " - " + Title'/>
How would I go about doing something like this in Razor or just solving a similar problem if I have the wrong approach ?
You could use ViewBag.Title
inside the layout:
<html>
<head>
<title>@ViewBag.Title - Site Name</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
and then define this variable inside the view:
@model AppName.Models.Product
@{
ViewBag.Title = Model.Name;
}
UPDATE:
Following on the comments question about default values you could use sections.
<html>
<head>
<title>
@if (IsSectionDefined("Title"))
{
RenderSection("Title")
}
else
{
<text>Some default title</text>
}
</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
and then inside your view you could redefine the section if you will:
@section Title {
<text>some redefined title here</text>
}
You can set and then overwrite this value in view as well using this approach:
@PageData["myTitle"] = "Title 1";
精彩评论