繁体   English   中英

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

[英]Call external controller method and render the view

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

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

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

问题是,当我尝试从TestController中的“测试”返回视图时,找不到该视图。

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文件夹中。 如何获得我的外部应用程序以渲染正确的视图?

您可以创建一个自定义视图引擎,但是如此处所述您需要进行许多修改:

  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" }; } } 

我仅覆盖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()); } 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM