Reputation: 3930
I have an ASP.NET, MVC, C# application that uses the _Layout.cshtml file. 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.
Such as in _Layout.cshtml have something like -
<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!
Upvotes: 1
Views: 892
Reputation: 2660
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>
}
Upvotes: 1
Reputation: 5793
Assuming you want to change more than just a simple text, you could use sections for that. For example, put this in _Layout.cshtml
:
@RenderSection("mySection", required: true)
and in each of your View then:
@section mySection
{
<div>Hello!</div>
}
Here's a nice blog with more info.
Upvotes: 4
Reputation: 2396
The ingenious solution: in the view add a variable to the 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.
Upvotes: 0