12

我正在尝试在ActionFilterAttribute我编写的自定义中设置布局路径,如下所示:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = "~/Views/Layouts/Test.cshtml"
        }
    }
}

在这里,Test.cshtml 是不同项目中的预编译视图(在 的帮助下RazorGenerator)。

但它给了我错误:

未找到视图“索引”或其主视图,或者没有视图引擎支持搜索的位置。搜索了以下位置:~/Views/Home/Index.cshtml ~/Views/Shared/Index.cshtml ~/Views/Home/Index.aspx ~/Views/Home/Index.ascx ~/Views/Shared/Index。 aspx ~/Views/Shared/Index.ascx ~/Views/Layouts/Test.cshtml

控制器实际上很简单:

[LayoutInjecter]
public class HomeController : Controller
{
    public ActionResult Index()
    {
       return View();
    }
}
4

3 回答 3

7

该错误表明LayoutInjecter工作正常。你说:

在这里,Test.cshtml 是不同项目中的预编译视图。

但是,开箱即用不支持使用来自不同(来自 Web 项目之外)的剃刀视图。但是,有一个工具可以预编译剃刀视图,然后您可以将它们放入任何名为RazorGenerator的 DLL 中。 编译器找不到指定的主布局文件并显示此错误。

有关更多信息,请查看

编辑: PrecompiledMvc​​ViewEngine 如何知道要渲染哪个视图?

PrecompiledMvcViewEngine 仍然依赖于 ASP.NET MVC Views 文件夹约定,使用相对文件路径来定位视图。但是,这有点误导。PrecompiledMvcViewEngine 不查看物理文件;它会查找System.Web.WebPages.PageVirtualPathAttributeRazor 单个文件生成器添加到它生成的每个视图中,包括视图的相对文件路径。

编辑 2:我相信您的问题的指导可以在GitHub中找到。

于 2015-11-26T08:25:37.020 回答
4

有用。确保布局路径"~/Views/Layouts/Test.cshtml"正确。

此外,请确保“Test.cshtml”是布局页面,而不是视图/部分视图。

于 2015-11-25T08:03:34.497 回答
3

更改result.MasterName = "~/Views/Layouts/Test.cshtml"result.MasterName ="~/Views/Shared/Test.cshtml"。按照惯例,框架在您的 asp.net mvc 解决方案中的 ~/Views/Shared/ 目录中查找布局页面。在我看来,您是动态地或在运行时选择母版页。

于 2015-11-28T00:48:35.757 回答