Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: How to handle model data that must go to every view?

So if there is some global state that every view of an MVC app will need to render ... for example: IsUserLoggedOn and UserName ... whats the appropriate way of getting that information to every view?

I understand that that part of the view should be in the master page or in a partial view thats added to the other views. But whats a good way to make sure the 'global' model data is passed to the view every time from all the relevant controllers and actions?

like image 471
codeulike Avatar asked Oct 27 '10 18:10

codeulike


People also ask

How do you pass model data into a view?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

Can you pass multiple models to a view?

In MVC we cannot pass multiple models from a controller to the single view.


1 Answers

After asking this, I found this good blog post by Steve Sanderson: http://blog.stevensanderson.com/2008/10/14/partial-requests-in-aspnet-mvc/

He suggests three different approaches:

  • Use a base controller class or ActionFilter to add the relevant model to the ViewData[] collection every time. I think a few people have suggested that sort of thing already.

  • Use Html.RenderAction() in the view ... and as he says:

If someone tells you that internal subrequests are bad because it “isn’t MVC”, then just bite them on the face immediately. Also ask them why they’re still willing to use Ajax, and even <IMG> tags for that matter, given that both are a form of subrequest.

  • Use 'Partial Requests' (he provides the code for this on his blog) which allow one controller to nest calls to other controllers into a sortof nested ViewData structure.
like image 145
codeulike Avatar answered Oct 20 '22 13:10

codeulike