5

I would like to create a static helper method that I can call from a view.

Is it possible for a helper method to have access to the current ViewContext without needing to explicitly pass the ViewContext to the method as a parameter?

Something like HttpContext.Current except for ViewContext.

1 Answer 1

8
public static class XTenshuns
{
    public static string MyHtmlHelper(this HtmlHelper helper)
    {
        // it's right here -> helper.ViewContext
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can I only do it via extension methods then? What if I wanted a plain ol' helper method?
Well, it couldn't be a plain old helper method. If you wanted to make it more lightweight, you could rip off some of the code from HtmlHelper to roll something similar... even then you'd need to add that as a property somewhere, probably a custom ViewPage. Nah, it's been written this way for a reason. Why so against HtmlHelper?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.