调用外部控制器方法并呈现视图

时间:2015-03-02 17:37:19

标签: c# .net asp.net-mvc razor model-view-controller

我正在使用一个名为MVCForum的项目,并在解决方案中创建了一个新项目,出于演示目的,我们称之为“ExternalApp”。

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

其中“TestController”是我的外部控制器。也就是说,控制器存在于ExternalApp中。

问题是当我尝试从TestController中的“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文件夹中。如何让我的外部应用程序呈现正确的视图?

2 个答案:

答案 0 :(得分:1)

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

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

  2. 创建自定义视图引擎:

    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"
           };
       }
    }
    
  3. 我只覆盖了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());
      }
      

答案 1 :(得分:0)

您可以使用Razor Generator之类的内容将您的视图编译到ExternalApp程序集中,也可以在一个站点下单独运行这两个应用程序。

相关问题