从asp.net类调用MVC视图会引发异常

我想获得MVC视图的HTML。 正在从ASCX.CS类呼叫。 (我试图注入MVC​​视图到ASPX页面)。 我的ASPX页面是动态创建的(控件是从代码后面添加的)。

我在这里找到了答案的一部分。 唯一的问题是这个扩展方法是为MVC控制器类制作的。

我在ASCX.CS的电话中做了什么:

 fCatEve.Controllers.ASPXTestController test = new Controllers.ASPXTestController();
      string htmlView = test.RenderView("Index", null);

在这个动作中,我唯一的问题是ControllerContext 。 我不知道如何设置这个类,所以它会找到我正在寻找的部分视图。

以下是我正在使用的方法(来自上面提到的页面):

public static class ControllerExtensions
{
    public static string RenderView(this Controller controller, string viewName, object model)
    {
        return RenderView(controller, viewName, new ViewDataDictionary(model));
    }

    public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData)
    {
        RouteData routeData = new RouteData();
  routeData.Values.Add("controller", controller);
  var controllerContext = new ControllerContext { Controller = controller, RouteData = routeData };

  var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);

        StringWriter stringWriter;

        using (stringWriter = new StringWriter())
        {
            var viewContext = new ViewContext(
                controllerContext,
                viewResult.View,
                viewData,
                controllerContext.Controller.TempData,
                stringWriter);

            viewResult.View.Render(viewContext, stringWriter);
            viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
        }

        return stringWriter.ToString();
    }
}

例外是:

RouteData必须包含一个名为'controller'的项目,其中包含一个非空字符串值。

尝试第一个答案后,这里是异常的堆栈跟踪:

System.Web.WebPages.DisplayModeProvider.GetDisplayMode(HttpContextBase上下文)在System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext,String []位置,字符串[] areaLocations,字符串locationsPropertyName System.Web.HttpContextBase.get_Items() ,System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext,String viewName,String masterName,Boolean useCache)在System.Web.Mvc.ViewEngineCollection上的字符串名称,字符串名称,字符串控制器名称,字符串cacheKeyPrefix,布尔useCache,字符串[]& 。在System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext,String viewName,String masterName)上的System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup,Boolean trackSearchedPaths)上的c__DisplayClass6.b__4(IViewEngine e)在C: ProjectsG_Test - KOPIJA fCatEve03 Solution中的fCatEve.Helpers.ControllerExtensions.RenderView(控制器控制器,字符串viewName,ViewDataDictionary视图数据) fCatEve fCatEve Helpers ControllerExtensions.cs:第43行在fCatEve.Controls.KoledarReception.PutValuesToTabControlEVEBEVEN(Panel paControl,REFields REField)in C: ProjectsG_Test - KOPIJA fCatEve03 Solution fCatEve fCatEve wf Controls KoledarReception。 ascx.cs:第2747行fCatEve.Controls.KoledarReception.PutValuesToTabControl()在C: ProjectsG_Test - KOPIJA fCatEve03 Solution fCatEve fCatEve wf Controls KoledarReception.ascx.cs中:第2710行在fCatEve.Controls.KoledarReception .Page_Load(Object sender,EventArgs e)in C: ProjectsG_Test - KOPIJA fCatEve03 Solution fCatEve fCatEve wf Controls KoledarReception.ascx.cs:System.Web.Util.CalliEventHandlerDelegateProxy.Callback(object sender ,EventArgs e)在System.Web.UI.Control.OnLoad(EventArgs e)在System.Web.UI.Control.LoadRecursive()在System.Web.UI.Control.LoadRecursive()在System.Web.UI.Control .LoadRecursive()在System.Web.UI.Control.LoadRecursive()在System.Web.UI.Control.LoadRecursive()在System.Web.UI.Page.ProcessRequ estMain(布尔includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)


以下是我用于生成PDF文件的单元测试之一的示例代码,不确定它是否对您有任何好处。

var controller = new MyAwesomePdfController();

var httpRequest = new HttpRequest("", "http://mySomething", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var routeData = new RouteData();
routeData.Values.Add("Controller", "MyAwesomePdf");  //must match your Controller name
routeData.Values.Add("Action", "Receipt");  //must match your Action name

var httpContextMock = new HttpContext(httpRequest, httpResponse)
{
    //this is probably irrelevant to you, can set user principal here
    //User = new GenericPrincipal(
    //  new GenericIdentity(username),
    //  userRoles //new string[0]
    //)
};

controller.ControllerContext = new ControllerContext(new HttpContextWrapper(httpContextMock), routeData, controller);

var receiptId = 1234;
var pdfResult = await controller.Receipt(receiptId) as ViewAsPdf;  //should return a pdf file

我重写了这个调用(最重要的是:稍后在MVC中使用的HttpContext.Current):

fCatEve.Controllers.ASPXTestController test = new Controllers.ASPXTestController();
      string htmlView = test.RenderView("Index", null, HttpContext.Current);

我也稍微改写了两种方法:

   public static string RenderView(this Controller controller, string viewName, object model, HttpContext currentContext)
    {
      return RenderView(controller, viewName, new ViewDataDictionary(model), currentContext);
    }


    public static string RenderView(this Controller controller, string viewName, ViewDataDictionary viewData, HttpContext currentContext)
    {
      var routeData = new RouteData();
      routeData.Values.Add("Controller", "ASPXTest");  //must match your Controller name
      routeData.Values.Add("Action", "Test");  //must match your Action name

      HttpContextWrapper wrapper = new HttpContextWrapper(currentContext);
      controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
      var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);

      StringWriter stringWriter;
      viewData = new ViewDataDictionary();


      using (stringWriter = new StringWriter())
      {
        var viewContext = new ViewContext(
            controller.ControllerContext,
            viewResult.View,
            viewData,
            controller.ControllerContext.Controller.TempData,
            stringWriter);

        viewResult.View.Render(viewContext, stringWriter);
        viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
      }

      return stringWriter.ToString();
    }
链接地址: http://www.djcxy.com/p/27993.html

上一篇: Calling MVC view from asp.net class throws exception

下一篇: How to map XML document to entity framework object?