Hello Razor MVC Gurus:
Newbie question.
Background. I have a custom IIdentity that is set in an HttpModule before it gets to controller & views. To use it, i have to do
MyIdentity myIdentity = (MyIdentity)((GenericPrincipal)context.User).Identity;
MyComplexUser user = myIdentity.User;
//user.name //user.location //user.username //etc
The problem is, I use the object in different places such as
- master layout
- Some sub level nested layouts
- Some partialviews
- Some views
It really depends on what properties of "MyComplexUser" object the views need.
Currently, in the views, I have to do this really complicated casting to get to a property. For instance, if I want the "Name" of the user, I need to do
@(((MyComplexUser)(((MyIdentity)((GenericPrincipal)context.User).Identity).User)).Name)
I suppose I could put it in the controllers and then populate the ViewBag with a ViewBag.MyUser property, but then
- I don't like to use ViewBag. I prefer strongly typed objects
- If I use a strongly typed object ("MyUser") for views, then I have to popular all those models with a "MyUser" property. Feels a bit dirty? As I like to keep my models clean and be specific to the views they are involved with. Besides, it gets unnecessarily repetitive.
- In places like master_layout.cshtml or partialviews, how do you access "MyUser" if I put them in a controller?
- Use RenderAction and build partialviews for each User property is an overkill?
Thanks. Again, I'm a newbie at MVC 4, any suggestion is greatly appreciate it.
BaseController
, which I've written. In this base class, I've wired up events of the lifecycle, such asExecuteCore
. I also use filters for things like this. On the view side, all my viewmodels inherit fromBaseVM
, where I place common properties, such as messages to the user, username and so on. – Andre Calil Jun 7 '13 at 14:23