V
V
Vyacheslav2017-09-24 19:47:35
ASP.NET
Vyacheslav, 2017-09-24 19:47:35

What is the recommended way in .NET Core to populate the master page (_Layout.cshtml) with dynamic content?

I'm using Razor pages from Core 2.0.
The task is that for each page that uses this Layout, certain methods of a certain class would be executed. For example, in the header of the page, you need to display the notification counter, and you need it to be recalculated every time. To do this, you need to create a connection to the database, while passing DbContext or ConnectionString from the settings to a specific method and execute the request. Those. you need to place some code somewhere and transfer some objects to it.
However, Layout does not have its own constructor for DI use and does not imply heavy coding at all. To do all this in Startup, in my opinion, is not competent, besides, you still need to somehow transfer the result to Layout.
There is another way to do such a thing through the ViewComponent.
But this option seems to me inappropriate, because. if I have a lot of dynamic data on the page, then creating a separate component for each of them is somehow too difficult.
So far, I have solved this problem using the object's static property, but this is contrary to the DI concept and in general ...
I would like to find out the general practice: 1) where to place this code 2) how to call it 3) how to pass the necessary objects to it (DbContext, Configuration) .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eRKa, 2017-09-25
@vpman

You can inject directly on the page
And in principle, in this case it can be a service that will work with the database.
But when I need to display content dynamics in the template, I implement it in js. Or is it important to solve it with Razor.

R
RouR, 2017-09-28
@RouR

@Html.PartialAction
Code - inside the controller of this PartialAction

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question