调用外部控制器方法并渲染视图

Call external controller method and render the view

我正在使用一个名为 MVCForum 的项目,并在解决方案中创建了一个新项目,为了演示目的,我们将其命名为 "ExternalApp"。

现在,我已将 ExternalApp 引用添加到 MCVForum 应用程序,并且可以调用控制器:http://mysite[.]com/TestController

其中 "TestController" 是我的外部控制器。也就是说,控制器位于 ExternalApp 中。

问题是,当我在 TestController 中尝试 return 来自 "Test" 的视图时,找不到该视图。

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Themes/Metro/Views/Test/Index.cshtml
~/Themes/Metro/Views/Extensions/Test/Index.cshtml
~/Views/Extensions/Test/Index.cshtml
~/Views/Test/Index.cshtml
~/Views/Test/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

该应用程序似乎在其自己的项目中寻找视图,而不是在 ExternalApp/Views 文件夹中。我怎样才能让我的外部应用程序呈现正确的视图?

您可以使用 Razor Generator 之类的东西将您的视图编译到您的 ExternalApp 程序集中,或者您可以 运行 将两个应用程序分别放在一个站点下。

您可以创建自定义视图引擎,但如前所述here您需要进行大量修改:

  1. 为了使我们的 MVCExternalApp 项目中的视图在运行时可用,必须将它们复制到 MVCForum 输出文件夹。除非您希望手动执行此操作,否则您必须明确告诉每个视图复制到输出。此选项强制文件进入 bin 文件夹。 对于每个视图,右键单击和 select 属性。将 'Copy to Output Directory' 选项更改为 'Copy Always'。这将确保在构建引用项目时始终将文件放入输出中。您还需要为 Web.config.

  2. 执行此操作
  3. 创建自定义视图引擎:

    public class CustomViewEngine: RazorViewEngine 
    {
       public CMSViewEngine()
       {               
           ViewLocationFormats = new string[] 
           {
               "~/Views/{1}/{0}.cshtml",
               "~/Views/{1}/{0}.vbhtml",
               "~/Views/Shared/{0}.cshtml",
               "~/Views/Shared/{0}.vbhtml",
               "~/bin/Views/{1}/{0}.cshtml", 
               "~/bin/Views/{1}/{0}.vbhtml", 
               "~/bin/Views/Shared/{0}.cshtml", 
               "~/bin/Views/Shared/{0}.vbhtml"
           };
    
           PartialViewLocationFormats = new[]
           {
               "~/Views/{1}/{0}.cshtml",
               "~/Views/{1}/{0}.vbhtml",
               "~/Views/Shared/{0}.cshtml",
               "~/Views/Shared/{0}.vbhtml",
               "~/bin/Views/{1}/{0}.cshtml", 
               "~/bin/Views/{1}/{0}.vbhtml", 
               "~/bin/Views/Shared/{0}.cshtml", 
               "~/bin/Views/Shared/{0}.vbhtml"
           };
       }
    }
    

我只覆盖了 PartialViewLocationFormats 和 ViewLocationFormats,但您可以根据需要覆盖其余位置;

  1. 在Global.asax中的Application_Start方法中注册视图引擎:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    
        //Remove all view engine
        ViewEngines.Engines.Clear();
    
        //Add Custom view Engine Derived from Razor
        ViewEngines.Engines.Add(new CustomViewEngine());
    }