ASP.NET MVC - get current controller and action name in helper

I am trying to create a custom html helper that will extract text from an XML file and display it in a view. XML is organized in a hierarchy where the top nodes represent the names of the controllers, following the names of the actions and then the individual keys.

The goal is to execute syntax, for example:

@Html.Show("Title") 

Where the assistant displays the name of the controller and the name of the action from the view where it was called.

Is there a way to get this information in the extension method of the html helper?

+7
source share
3 answers

You can get the current controller and action from htmlHelper.ViewContext.RouteData . Use the extension method below to get the corresponding value from xml:

 //make sure you include System.Xml.XPath, otherwise extension methods for XPath //won't be available using System.Xml.XPath; public static MvcHtmlString Show(this HtmlHelper htmlHelper, string key) { XElement element = XElement.Load("path/to/yourXmlfile.xml"); RouteData routeData = htmlHelper.ViewContext.RouteData; var keyElement = element.XPathSelectElements(string.format("//{0}/{1}/{2}", routeData.GetRequiredString("controller"), routeData.GetRequiredString("action"), key) ).FirstOrDefault(); if (keyElement == null) throw new ApplicationException( string.format("key: {0} is not defined in xml file", key)); return new MvcHtmlString(keyElement.Value); } 
+8
source

Even simpler:

 htmlHelper.ViewContext.RouteData.Values["controller"] 

and

 htmlHelper.ViewContext.RouteData.Values["action"] 

gives you the name of the controller and actions accordingly.

+12
source

Here is the name of the action:

 ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() 
+8
source

All Articles