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?
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.
In MVC we cannot pass multiple models from a controller to the single view.
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.
ViewData
structure.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With