Click here to Skip to main content
15,042,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm making a "News" sidebar that should persist on the website, through all other views, with data fetched from the database into the ViewBag.

How should I architect the site to persist a partial view (or section...) that references the same data across all pages? The separation of models/controllers and views stymies this design when other site views depend on different controllers.

What I have tried:

I crafted this as a partial view called by _layout and stocked it with data queried in the Home controller and saved to the ViewBag for access by the called partial view.

However, when other pages in the site load, they don't have access to the data model that was originally stocked by the HomeController.
Updated 6-Aug-16 16:58pm
John C Rayan 28-Jul-16 4:14am
If you use partialview with model passed in then you have to make sure that the model is passed to the partial from all pages.

However , in your case if you are using _layout then you don't have to use partialview because the _layout is automatically shared all the pages.
So you have to re-visit your design and make it simpler.
Member 4594688 28-Jul-16 17:06pm
That's the problem. The _layout architecture allows easy reusability of a VISUAL component, but what about DATA that is presented by that component? I don't want to have to extract the same data for every single view in the website.

My design is "simple" but it's not working, so I may well need to make it more complex to get it to work.

1 solution

I found a solution that seems more flexible architecturally than app session, and since the data may change it will update the data when the forms are reloaded.

Upon reflection I realized that I'm not so much concerned about fetching the data only once in the session (and it may change in the background anyway), than with avoiding repetitive coding of the fetch in every controller.

So creating a service and using dependency injection to inject it directly into the _Layout view (or a partial view called by it) seems like the perfect solution. I never have to touch a controller to provide this data in a side panel throughout the website.

This link provides an easy-to follow example:

Injecting Services Into Views — ASP.NET documentation

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900