MVC 4:区域,路由和子文件夹中的视图

时间:2014-03-19 09:43:20

标签: asp.net-mvc routing asp.net-mvc-areas

我在我的应用程序中添加了一个区域。它被称为“例子”。有一条默认路线:

context.MapRoute(
    "Examples_default",
    "Examples/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);

如果我有一个名为“MyExampleController.cs”的控制器和一个默认位于Views / MyExample / Index.cshtml下的View,这个工作正常。 我可以访问网址"http://localhost/Examples/MyExample/Index"

我想要的只是在视图下创建一个子文件夹以添加一个更高级别的组织。即在视图下创建一个文件夹“NewExamples”并在那里移动MyExample。所以我可能有以下结构

Views/NewExamples/MyExample/Index.cshtml
Views/OldExamples/Example123/Index.cshtml

我想要一个网址"http://localhost/Examples/NewExamples/MyExample/Index"

我正在努力寻找一条路线。我的方法是在默认路线之前添加路线:

context.MapRoute(
    "Examples_newexamples",
    "Examples/NewExamples/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);

但这不起作用。我点击了我的控制器,但后来我收到了服务器错误

未找到视图“索引”或其主控,或者没有视图引擎支持搜索的位置。搜索了以下位置:

~/Areas/Examples/Views/MyExample/Index.aspx
~/Areas/Examples/Views/MyExample/Index.ascx
~/Areas/Examples/Views/Shared/Index.aspx
~/Areas/Examples/Views/Shared/Index.ascx
...
~/Areas/Examples/Views/MyExample/Index.cshtml
~/Areas/Examples/Views/MyExample/Index.vbhtml
~/Areas/Examples/Views/Shared/Index.cshtml
~/Areas/Examples/Views/Shared/Index.vbhtml
...

因此它甚至没有尝试查看NewExamples子文件夹。

是否有正确的路线来包含此子文件夹?

1 个答案:

答案 0 :(得分:2)

为此目的,我通常使用Route属性:

[Route("~/Examples/NewExamples/MyExample/{id}")]
public ActionResult MyExample(it id)
{
 ...
}