为什么MVC视图需要存在于View目录中才能工作?

时间:2011-02-03 16:55:01

标签: asp.net-mvc-3 razor viewbag

我一直在编写一个cms,MVC被用作生成页面的主要引擎。

我顺利,但希望能够为每个网站创建一个独特的剃刀模板,如果需要的话,可能每个视图。

我的规则是每个项目都必须有一个与网址链​​接的唯一代码。

每个项目站点的资产以​​与该项目相关的位置的方式存储。

因此,与项目C0001关联的资产将存储在assets\C0001\和C0002:assets\C0002\中,依此类推。

为了保持整洁,我想做的是将剃须刀模板与位于assets\[ProjectCode]位置的项目相关联,但问题是我收到有关ViewBag not existing in context的错误

所以这不起作用:

Layout = string.Concat("~/assets/",ViewBag.ProjectNumber,"/_Layout.cshtml");

以下内容将呈现页面:

Layout = string.Concat("~/Views/Shared/_",ViewBag.ProjectNumber,"Layout.cshtml");

我猜第一个布局没有呈现,因为它在已知的视图搜索区域之外?但是当我告诉它文件的位置时,我不知道问题是什么?

我很高兴使用示例2中的代码,但可能意味着在相当多的项目网站之后,共享视图会变得非常繁忙。

只是想知道是否需要在Views目录中存在视图?

2 个答案:

答案 0 :(得分:7)

您需要复制位于Views目录中的web.config并将副本放在Assets目录中。由于您需要提供布局的完整路径,这不是搜索路径问题,因此需要web.config中的信息才能正确初始化视图。

答案 1 :(得分:4)

默认情况下,RazorViewEngine配置为查看Views目录。

您可以通过创建具有不同路径的自己的RazorViewEngine实例并将其添加到ViewEngines.Engines来更改此设置。

其默认路径为

AreaViewLocationFormats = new[] {
    "~/Areas/{2}/Views/{1}/{0}.cshtml",
    "~/Areas/{2}/Views/{1}/{0}.vbhtml",
    "~/Areas/{2}/Views/Shared/{0}.cshtml",
    "~/Areas/{2}/Views/Shared/{0}.vbhtml"
};
AreaMasterLocationFormats = new[] {
    "~/Areas/{2}/Views/{1}/{0}.cshtml",
    "~/Areas/{2}/Views/{1}/{0}.vbhtml",
    "~/Areas/{2}/Views/Shared/{0}.cshtml",
    "~/Areas/{2}/Views/Shared/{0}.vbhtml"
};
AreaPartialViewLocationFormats = new[] {
    "~/Areas/{2}/Views/{1}/{0}.cshtml",
    "~/Areas/{2}/Views/{1}/{0}.vbhtml",
    "~/Areas/{2}/Views/Shared/{0}.cshtml",
    "~/Areas/{2}/Views/Shared/{0}.vbhtml"
};

ViewLocationFormats = new[] {
    "~/Views/{1}/{0}.cshtml",
    "~/Views/{1}/{0}.vbhtml",
    "~/Views/Shared/{0}.cshtml",
    "~/Views/Shared/{0}.vbhtml"
};
MasterLocationFormats = new[] {
    "~/Views/{1}/{0}.cshtml",
    "~/Views/{1}/{0}.vbhtml",
    "~/Views/Shared/{0}.cshtml",
    "~/Views/Shared/{0}.vbhtml"
};
PartialViewLocationFormats = new[] {
    "~/Views/{1}/{0}.cshtml",
    "~/Views/{1}/{0}.vbhtml",
    "~/Views/Shared/{0}.cshtml",
    "~/Views/Shared/{0}.vbhtml"
};