[英]ASP.NET, MVC, C# application - modify _Layout.cshtml for different Views
I have an ASP.NET, MVC, C# application that uses the _Layout.cshtml file. 我有一个使用_Layout.cshtml文件的ASP.NET,MVC,C#应用程序。 I would like to use the _Layout.cshtml file for multiple Views, but depending on which view is being displayed, I would like to alter the _Layout.cshtml a little.
我想将_Layout.cshtml文件用于多个视图,但是根据要显示的视图,我想稍微改变_Layout.cshtml。
Such as in _Layout.cshtml have something like - 如在_Layout.cshtml中有类似的内容-
<div>I would like to say </div>
@if(View = "View1")
{
<div>Hello!</div>
}
@else
{
<div>Goodbye!</div>
}
<div>Have a great day!</div>
Can someone tell me how this can be done? 有人可以告诉我该怎么做吗? Thanks!
谢谢!
Assuming you want to change more than just a simple text, you could use sections for that. 假设您不仅要更改简单的文本,还可以使用相应的部分。 For example, put this in
_Layout.cshtml
: 例如,将其放在
_Layout.cshtml
:
@RenderSection("mySection", required: true)
and in each of your View then: 然后在您的每个视图中:
@section mySection
{
<div>Hello!</div>
}
Usually you wanted to check the against the action rather than views. 通常,您想对照操作而不是视图来检查。 You would want to do something like this
你想做这样的事情
@if(Html.ViewContext.RouteData.Values["Controller"] == "Home" && Html.ViewContext.RouteData.Values["Action"] == "Index") {
<div>Hello!</div>
}else {
<div>Goodbye!</div>
}
The ingenious solution: in the view add a variable to the ViewBag. 巧妙的解决方案:在视图中向ViewBag添加变量。 Like so:
像这样:
@ViewBag.Foo="bar"
Before you define which view is rendered. 在定义渲染哪个视图之前。 And make an if in the layout based on it.
并在此基础上进行布局。
Though this is not the best practice approach - I personally would go for different layouts perhaps. 尽管这不是最佳实践方法-我个人可能会选择不同的布局。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.