Admir Tuzović
Admir Tuzović

Reputation: 11177

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

I'm trying to create custom html helper that will retrieve some text from XML file and render it on the view. XML is organized in hierarchy where top nodes represent controller names, following the action names and then individual keys.

Goal is to accomplish syntax such as:

@Html.Show("Title")

Where helper would infer controller name and action name from the view where it was called.

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

Upvotes: 10

Views: 13300

Answers (3)

David R
David R

Reputation: 166

Even simpler:

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

and

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

gives you the controller and action name, respectively.

Upvotes: 14

karaxuna
karaxuna

Reputation: 26940

Here is Action name:

ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString()

Upvotes: 9

Abdul Munim
Abdul Munim

Reputation: 19217

You can retrieve current controller and action from htmlHelper.ViewContext.RouteData. Use the extension method below to retrieve 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);
}

Upvotes: 10

Related Questions