gbjbaanb
gbjbaanb

Reputation: 52679

asp.net core pass data from content page to layout

I'm trying to set a master layout.cshtml page that works consistently for all page except for one or two (typically login and logout). In my layout I'd like to display some elements that I want to not display for these special pages.

I've seen partial views and sections and they all seem to work "backwards" to the way I want - in this case I want the default to be 'display all the elements', but for special pages I want to be able to turn an element off.

I've seen previous code that uses PageData to pass a variable to the layout (which seemed very useful as I could slap a bool in the relevant pages and check it in the layout) but this seems to have been removed. Are there any other ways that work without involving the controller or updating every page to display the bits I want hidden on just 1 page?

Upvotes: 4

Views: 5555

Answers (2)

Aminur Rahman
Aminur Rahman

Reputation: 410

You can try this to pass ViewData in _Layout page in asp.net mvc

public class DynamicMenuAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
       base.OnActionExecuted(filterContext);
       var result = filterContext.Result as ViewResult;
       result.ViewData["key"] = "Hello Bangladesh";
    }
}

Add Dependency Injection into Startup.cs file

services.AddMvc(
    config =>
    {
       config.Filters.Add(new DynamicMenuAttribute());
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Now you can you ViewData["key"] in _Layout.cshtml

Upvotes: -2

Chris Pratt
Chris Pratt

Reputation: 239290

There's a number of different ways you can achieve this. If you want to simply "turn off" an area of the page, the simplest approach is probably with ViewData. Something like:

_Layout.cshtml

@if (ViewData["ShowThis"] as bool? ?? true)
{
    <!-- HTML here -->
}

This will cause it to default to true (show the HTML) if the ViewData key is not defined, so then in your views where you want to disable it, you'd just need to define it as false:

SomeView.cshtml

@{
    ViewData["ShowThis"] = false;
}

Alternatively, you can use sections. This would give you the ability to optionally replace the HTML with something else.

_Layout.cshtml

@if (!IsSectionDefined("Foo"))
{
    <!-- HTML here -->
}
else
{
    @RenderSection("Foo", required: false)
}

Then, in your view, you simply define the section. If you want to display nothing, you can just define it empty:

SomeView.cshtml

@section Foo {}

Or you can can actually put something in there to replace the area with:

@section Foo
{
    <!-- alternate HTML here -->
}

Upvotes: 12

Related Questions