How To Get The Episerver Action, Controller and Tag Data Out Of The Http Context In MVC

Recently, I had a task of writing a custom cache provider, which was fun.  The reasons and tribulations of that task are outside the scope of this article, but as part of the journey, I needed to call a lot of block controllers directly and do all sorts of other strange things.  Unless you're trying to write a custom cache, a customer content rendered or content area render, I think the code below is probably not the right solution for the majority of people.  If you have stumbled across this article and you have a problem like passing data from a block to a controller, or passing information from a view to a controller then there are better alternatives than you can find in this article.  For those people, I would recommend reading, EPiServer 7 Routing For Dummies. I understand how frustrating it is when you see snippets of code and you're not quite sure where it needs to go, so I'm going to break these snippets by area:

Creating a Custom HTML Helper, Custom Content Area Rendered, ContentRender

In these methods you will have access to the HTML Helper. This is the main source of getting the information you need: Getting Access To The Current Action Being Called
  var actionName = helper.ViewContext.RouteData.Values["action"].ToString();
Getting Access To The Current Controller Being Called
  var controllerName = helper.ViewContext.RouteData.Values["controller"].ToString();
Getting Access To The Current Tags Being Called
                var tag = string.Empty;
                if (helper.ViewContext.Controller.ControllerContext.ParentActionViewContext != null)
                    tag = helper.ViewContext.Controller.ControllerContext.ParentActionViewContext.ViewData["tag"].ToString();
(Note: I have never got this working but it might help someone!)

In Your Controller

  var actionName = RouteData.Values["action"].ToString();
Getting Access To The Current Controller Being Called
  var controllerName = RouteData.Values["controller"].ToString();
Getting Access To The Current Tags Being Called
ControllerContext.ParentActionViewContext.ViewData["tag"] as string ?? "Default";

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top