HtmlHelper in controller

2019-05-04 11:07发布

问题:

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

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());

回答1:

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?