简体   繁体   中英

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. 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!

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM