在 Razor 视图中覆盖变量
Overriding variables in Razor views
我对整个 AspNetCore MVC 场景还很陌生,在编写 html.
时遇到了一些麻烦
我有以下L
_layout.cshtml
@{
bool showTitle = true;
}
....
if (showTitle)
{
....
}
Page.cshtml
@{
showTitle = false;
}
克莱里
我希望默认显示页面标题,并可以选择在特定视图文件中隐藏它。但是,我无法覆盖 showTitle
变量,因为它在视图文件中是未知的。
我通常使用_layout.cshtml
中的逆逻辑来解决这个问题
@if (ViewData["hideTitle"] != null)
{
... render something
}
else
{
... default behaviour, render something else
}
通常用于覆盖这样的页面标题:
_layout.cshtml
@if (ViewData["Title"] != null)
{
<title>@ViewData["Title"] | My Fantastic Website</title>
}
else
{
<title>My Company | My Fantastic Website</title>
}
并且您可以像这样在具体视图中覆盖页面标题:
@{
ViewData["Title"] = "About Us";
}
未定义 ViewData["Title"]
的视图将获得默认标题 <title>My Company | My Fantastic Website</title>
。
如何把变量放在ViewBag中,然后在Controller中设置
_layout.cshtml
if (ViewBag.ShowTitle == null || ViewBag.ShowTitle == true)
{
...
}
控制器
{
ViewBag.ShowTitle = false;
return View();
}
我对整个 AspNetCore MVC 场景还很陌生,在编写 html.
时遇到了一些麻烦我有以下L
_layout.cshtml
@{
bool showTitle = true;
}
....
if (showTitle)
{
....
}
Page.cshtml
@{
showTitle = false;
}
克莱里
我希望默认显示页面标题,并可以选择在特定视图文件中隐藏它。但是,我无法覆盖 showTitle
变量,因为它在视图文件中是未知的。
我通常使用_layout.cshtml
中的逆逻辑来解决这个问题@if (ViewData["hideTitle"] != null)
{
... render something
}
else
{
... default behaviour, render something else
}
通常用于覆盖这样的页面标题:
_layout.cshtml
@if (ViewData["Title"] != null)
{
<title>@ViewData["Title"] | My Fantastic Website</title>
}
else
{
<title>My Company | My Fantastic Website</title>
}
并且您可以像这样在具体视图中覆盖页面标题:
@{
ViewData["Title"] = "About Us";
}
未定义 ViewData["Title"]
的视图将获得默认标题 <title>My Company | My Fantastic Website</title>
。
如何把变量放在ViewBag中,然后在Controller中设置
_layout.cshtml
if (ViewBag.ShowTitle == null || ViewBag.ShowTitle == true)
{
...
}
控制器
{
ViewBag.ShowTitle = false;
return View();
}