I have a pretty common issue: I need to know the name of current user and also name of the current controller so I can highlight/disable some links.
Here's some solutions I found by myself:
Get all what's needed inside
PartialView
.I have a PartialView inside my page layout, that takes user name like this:
@{ var userName = Context.ToContext().GetUser<Agent>().Name; }
And here's the way I take controller name:
@{ var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString(); }
I have some problem with this code, for it is suspected to ruin MVC pattern. I have another solution, which I consider even more stupid.
I've created new controller called like
ContextController
:public class ContextController : BaseController // BaseController is just a facade { public string GetUserName() { return Context.GetUser<Agent>().Name; } }
Here's the problem: I cannot get controller name with this way, because it will always be like "Context", which is useless for me. And I also get the name on view like this:
@{ var userName = Html.Action("GetUserName", "Context"); }
The last way I figured out is to pass needed strings through
ViewData
. But I have about 18 controllers and some of 'em have like 3 methods, returningViewResult
. It's not bad design, it's just reality. And I don't actually want to create and passViewDataDictionary
for every single method, that returnsViewResult
. Maybe I could extend myBaseController
, soViewDataDictionary
for every page will always haveuserName
andcontrollerName
?But here comes another problem: I have whole lot of AJAX in my project, and it seems to me not legit enough to pass unused data every time controller action is called.
If you know of a better solution, I'd be happy to hear it.