Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc razor - Send data to main layout

I am newbie in asp.net mvc. I created an asp.net mvc4 empty application and added an entity model to it. I have a layout page which I want to display menu categories,header,footer vb.But how can I send the data contains one more entity object(last posts,categories,tags) to layout page ? Thanks

like image 439
Mustafa Avatar asked Dec 16 '22 09:12

Mustafa


1 Answers

If you want to pass data (coming from database I assume) to the layout view you are facing a scenario where you have data that is passed to every page in your application. So what I would do is create a base controller from which all your controllers will inherit:

public class BaseController : Controller
{
   public LayoutModel model;

   public BaseController()
   {
       // Here you will use some business logic to populate your Layout Model
       // You might also consider placing this model into the cache to prevent constant fetching of data from the database on each page request.
       model = _service.Populate();
       ViewBag.LayoutModel = model;
   }
}

As you can see I used the constructor of the base controller to fetch the data needed for your layout view. I made a property named model and used some business logic method called Populate (you need to write this yourself) to populate the model variable. Then I place the model into the ViewBag.

Once I have this set up then every controller I make in my solution needs to inherit from the base controller:

public class HomeController : BaseController
{
   // Controller code here...
}

which means that every controller can now access the model property from the base controller.

From here you can use the ViewBag.LayoutModel on each view like this (declare a local variable at the top of the view and cast it into the underlying type):

@{
   LayoutModel MenuModel = ViewBag.LayoutModel;
}

and then use it like this:

@MenuModel.SomeProperty

This is just one of the ways to do it but there are other less/more complex ways. You need to do some research on your own and see which technique fits you the best...

like image 162
Marko Avatar answered Feb 02 '23 15:02

Marko