Jordan
Jordan

Reputation: 9901

How can I get the current controller from within a MVC HtmlHelper extension?

Like with most implementations of MVC, all of my abstract services are available in the Controller. Well, I am creating the following HTML helper extension to allow embedding application settings into the HTML as hidden inputs:

public static MvcHtmlString HiddenForSetting<TResult>(this HtmlHelper htmlHelper, Expression<Func<IMyAppSettings, TResult>> expression, string name = null)
{
    IMyAppSettings settings = null;

    return MyHtmlHelpers.HiddenForSetting<IMyAppSettings, TResult>(htmlHelper, expression, settings, name);
}

The helper provides the settings object and allows the consumer to select which property to embed. IMyAppSettings is such a service. So I want to get this service off of the controller itself. Is there a means of accessing the controller from within this static helper extension method?

Note: I DO NOT need the controller name! I need the controller instance itself.

Upvotes: 1

Views: 675

Answers (1)

user47589
user47589

Reputation:

You can get the controller using:

htmlHelper.ViewContext.Controller

It's a ControllerBase. If you know the type of controller, you can cast it as needed.

Upvotes: 3

Related Questions