4

I need a HtmlHelper instance in my controller.

How can I instantiate one? thanks

This does not build:

var h = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary()), new ViewPage());

Here is a screenshot of the error enter image description here

Also, when I look at the list of methods under var h, I only see my custom extension methods and no regular ones like ActionLink. So that one needs to list as well. (solved by sternr)

Solution:

  1. Ensure System.Web.Mvc.Html is included.

  2. Here is the code to instantiate a HtmlHelper.

    System.IO.TextWriter writer = new System.IO.StringWriter();

    var html = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "omg"), new ViewDataDictionary(), new TempDataDictionary(), writer), new ViewPage());

Valamas
  • 24,169
  • 25
  • 107
  • 177

1 Answers1

2

HtmlHelper.ActionLink and most of the methods you'r probably looking for are extension methods declared under the System.Web.Mvc.Html namespace.

As for instantiating\using HtmlHelper inside your controller - this is a bad practice as your clearly combine UI code with Controller code. What are you trying to acheive?

sternr
  • 6,216
  • 9
  • 39
  • 63
  • thanks for the System.Web.Mvc.Html namespace trick. I need to pass the HtmlHelper to a class library to do some work. I have updated my question with a screenshot of the error. – Valamas Jul 31 '11 at 05:52
  • 1
    Voted down as does not answer question of how to get reference to HtmlHelper in controller. – Mark Micallef Dec 11 '15 at 05:34