我有一个MVC 5项目,包含许多控制器,模型和页面。为了使它们更易于维护,我将一些相关文件移动到一个名为Mail的新区域。
项目结构如下:
Automation (project's name)
|- Controllers
|- Views
|- Models
└── Areas
└── Mail
└── Models
└── Controllers
└── MailboxController
└── Views
└── Inbox.cshtml
我执行了以下步骤,以便能够加载新移动的视图:
将Rout添加到MailAreaRegistaration.cs,如下所示:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Mail_default",
"Mail/{controller}/{action}/{id}",
new { action = "Inbox", id = UrlParameter.Optional},
new [] { "Automation.Areas.Mail.Controllers" });
}
在项目的RoutConfig文件中更改MapRout方法,如下所示:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Dashboards", action = "Dashboard_Main", id = UrlParameter.Optional },
namespaces: new [] {"Automation.Controllers"}
);
}
主View文件夹中的所有页面都按预期呈现,但是当我想在Mail区域中加载inbox.cshtml时,会显示以下错误:
The view 'inbox' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Areas/Mail/Views/mailbox/inbox.aspx
~/Areas/Mail/Views/mailbox/inbox.ascx
~/Areas/Mail/Views/Shared/inbox.aspx
~/Areas/Mail/Views/Shared/inbox.ascx
~/Views/mailbox/inbox.aspx
~/Views/mailbox/inbox.ascx
~/Views/Shared/inbox.aspx
~/Views/Shared/inbox.ascx
~/Areas/Mail/Views/mailbox/inbox.cshtml
~/Areas/Mail/Views/mailbox/inbox.vbhtml
~/Areas/Mail/Views/Shared/inbox.cshtml
~/Areas/Mail/Views/Shared/inbox.vbhtml
~/Views/mailbox/inbox.cshtml
~/Views/mailbox/inbox.vbhtml
~/Views/Shared/inbox.cshtml
~/Views/Shared/inbox.vbhtml
我测试了收件箱页面的下方网址,但没有人成功
我该如何解决?感谢
答案 0 :(得分:0)
假设你有MailboxController
这样的课程:
public class MailboxController : Controller
{
// default action in area
public ActionResult Inbox()
{
return View();
}
}
首先,创建自定义类以在以下示例给出的区域文件夹中执行视图搜索:
namespace Automation
{
public class CustomRazorEngine : RazorViewEngine
{
public CustomRazorEngine()
{
// short note:
// {2} = area name
// {1} = controller name
// {0} = action name
AreaViewLocationFormats = new[]
{
// add these routes in area scope
"~/Areas/{2}/Views/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
};
ViewLocationFormats = new[]
{
// example routes
"~/{1}/{0}.cshtml",
"~/Views/{1}/{0}.cshtml"
}
FileExtensions = new[]
{
"cshtml"
};
}
}
}
然后我在Global.asax中的Application_Start
方法中注册自定义视图引擎:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ViewEngines.Engines.Add(new CustomRazorEngine()); // customized view search engine
// other settings here
}
使用以上设置,以下网址应该有效:
http://localhost:port/Mail/Mailbox
http://localhost:port/Mail/Mailbox/Inbox
参考文献:
答案 1 :(得分:0)
解决此问题的最简单方法是遵循MVC约定并将Inbox.cshtml
文件移动到MVC所期望的Areas\Mail\Views\Mailbox\Inbox.cshtml
位置(您只缺少Mailbox
文件夹)。
但是,如果您打算根据自己的想法自定义视图位置,请使用Tetsuya's solution。