【发布时间】:2013-11-15 01:32:16
【问题描述】:
我正在使用 Razor 引擎来呈现我的视图,并且我想对其进行一些自定义以获得与默认行为不同的行为。
我对后面的相同数据有不同的视图,我想重用它们,但我要在外部指定子文件夹的更改。
这就是树:
- 查看次数
- 1
- 控制器名称
- 文件.cshtml
- 共享
- _Layout.cshtml
- 控制器名称
- 2
- 控制器名称
- 文件.cshtml
- 共享
- _OtherLayout.cshtml
- 控制器名称
- 等
- 1
唯一不同的是子文件夹,其他都一样(除了cshtml文件的内容^^)。如何根据我的意愿切换到正确的文件夹?
我的第一个方法(不是很成功)是创建一个 CustomViewEngine(然后在 Global.asax 中调用它),但现在我得到了 404。 (id 将在稍后使用 ViewBag 设置为动态)
public class CustomViewEngine : RazorViewEngine
{
public CustomViewEngine()
{
ViewLocationFormats = new[]
{
"~/Views/%1//{1}/{0}.cshtml",
"~/Views/%1//Shared/{0}.cshtml"
};
MasterLocationFormats = new[]
{
"~/Views/%1/{1}/{0}.cshtml",
"~/Views/%1/Shared/{0}.cshtml",
};
PartialViewLocationFormats = new[]
{
"~/Views/%1/{1}/{0}.cshtml",
"~/Views/%1/Shared/{0}.cshtml"
};
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
var id = "1";
return base.CreatePartialView(controllerContext, partialPath.Replace("%1", id));
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
var id = "1";
return base.CreateView(controllerContext, viewPath.Replace("%1", id), masterPath.Replace("%1", id));
}
protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
{
var id = "1";
return base.FileExists(controllerContext, virtualPath.Replace("%1", id));
}
}
【问题讨论】:
-
真正的问题是什么?你想知道如何让
id动态化吗? -
我想我可以得到它。主要问题是如何在视图之间切换。如果我将我的 id 更改为“2”(动态或非动态),我希望引擎在子文件夹 2 等中查找视图。
-
你调试过你的代码吗?您的代码是否命中
FileExists方法?如果没有,那么您的CustomViewEngine根本没有被使用。 -
我什至在使用任何东西之前就已经 404 了……即使我正在尝试 @alex-v-kostyukov 的基本功能,方法是将正确的路径返回到我的视图(并停用那个自定义引擎)
-
然后让我们看看您在
Global.asax文件和路线注册部分中有什么。
标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor