rjzii
rjzii

Reputation: 14533

How do you create an HtmlHelper outside of a view in ASP.NET MVC 2.0?

We are in the process of upgrading an ASP.NET MVC 1.0 application to the 2.0 release and some of the code requires the use of LinkExtensions which require an HtmlHelper to render. While we know that some of the code doesn't follow the MVC model correctly and are in the process of recoding as needed, we need something to work so get the application to build.

Here is the current syntax that we have that works under ASP.NET MVC 1.0:

public static HtmlHelper GetHtmlHelper(ControllerContext context)
{
    return new HtmlHelper(new ViewContext(context,
                                          new WebFormView("HtmlHelperView"),
                                          new ViewDataDictionary(),
                                          new TempDataDictionary()),
                          new ViewPage());
}

The error that we are getting is as follows:

Error 1 'System.Web.Mvc.ViewContext' does not contain a constructor that takes 4 arguments

Upvotes: 4

Views: 2802

Answers (2)

Mattias Jakobsson
Mattias Jakobsson

Reputation: 8237

The problem is (as the error message suggests) that there no longer is a constructor of ViewContext that takes 4 parameters. They have added a fifth that is a textwriter. You can create a viewcontext in this way:

new ViewContext(context,
                                      new WebFormView("HtmlHelperView"),
                                      new ViewDataDictionary(),
                                      new TempDataDictionary()),
                      new ViewPage(), context.HttpContext.Response.Output);

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

There's an additional argument which takes a TextWriter:

var viewContext = new ViewContext(
    context,
    new WebFormView("HtmlHelperView"),
    new ViewDataDictionary(),
    new TempDataDictionary(),
    context.HttpContext.Response.Output
);

The question here is why would you need to instantiate a htmlHelper yourself instead of using the one that's provided in the views?

Upvotes: 5

Related Questions