• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 223
  • Last Modified:

How do I display information gathered from database in _layout templace? MVC4

Hi

I would like to pull some information out of the database depending on some information I store to a session.

Using asp we do that in the load event of a page and then assign the result to a asp label.

I am able to do it in the views but I am not sure how to do it in a template.

Any help is always appreciated.
0
elmbrook
Asked:
elmbrook
1 Solution
 
Craig WagnerSoftware ArchitectCommented:
You should not be accessing the database from a view, you should do it from the controller method that renders the view and pass whatever information is needed by the view in a model/viewmodel.

There are a couple of options for getting that information into the layout page.

1. Create a base class viewmodel and have all viewmodels inherit from it. Make the layout page use the base class as its strongly-typed view.

2. Put everything needed by the layout page into ViewData/ViewBag and access it that way from the layout page.

Using #2 it's pretty easy to create an action filter on your base controller class that populates the ViewBag so you're sure it gets done on every action.

P.S. You'll do better with MVC if you stop thinking in terms of WebForms and page events. WebForms and MVC are fundamentally different and trying to look for analogous functionality is just going to hurt you in the long run.
0
 
elmbrookAuthor Commented:
Thanks Craig.

This is my first MVC project and you are right about stopping thinking in terms of webforms.
However, I needed to explain how I wanted it to work .

In the end I went with solution 2 which was easy to implement.

Thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now