Pass Data from Middleware to _Layout View

Viewed 1684

My asp.net-core Application has a sidebar in _Layout.cshtml. The sidebar is dynamically, so I need PageData. I tryed to pass the PageData from my PagesMiddleware to the View (I don't want to forward the PageData in every Controller for the Views).


Don´t want this: [PagesMiddleware] -> Controller -> _Layout.cshtml

PagesMiddleware: context.Items.Add("pages", pages);

every Controller: ViewData["Pages"] = TempData["pages"];

_Layout: @ViewData["Pages"]


Is there something like this: [PagesMiddleware] -> -> _Layout.cshtml

PagesMiddleware: ViewData["Pages"] = pages;

_Layout: @ViewData["Pages"]


PageData can be a string. How can i pass a string from Middleware to _Layout View without extra (redundant) Code in all Controllers?

1 Answers

As per comment on the post, HttpContext object is always accessible from a Razor view

Middleware

context.Items.Add("pages", pages);

View

@{
    var pages = Context.Items["pages"];
}
Related