问题
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
回答1:
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?
回答2:
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);
来源:https://stackoverflow.com/questions/3084523/how-do-you-create-an-htmlhelper-outside-of-a-view-in-asp-net-mvc-2-0