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

拜拜、爱过 提交于 2019-12-10 09:22:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!