c# - 在自定义 View 引擎中使用子文件夹

标签 c# asp.net-mvc-5 viewengine

为了在我的新 MVC 5 应用程序中组织我的 View ,我设置了一个文件夹结构,如下所示:

Views
|-- Account
|   |-- Partials
|       |-- EditUser.cshtml
|       |-- ListUsers.cshtml
|   |-- Home.cshtml
|
|-- Admin
    |-- Partials
        |-- AnotherPartialView.cshtml

现在,我想为此实现一个自定义 View 引擎,这样我就不必在我的主视图文件夹中一直指定 Partials 文件夹的完整路径。

我创建了一个像这样的自定义 View 引擎:

public class CustomViewEngine : RazorViewEngine
{
    public CustomViewEngine()
        : base()
    {

        var viewLocations = new[] {  
            "~/Views/{1}/{0}.cshtml",  
            "~/Views/Shared/{0}.cshtml",  
            "~/Views/{1}/Partials/{0}.cshtml"

        };

        this.PartialViewLocationFormats = viewLocations;
        this.ViewLocationFormats = viewLocations;


    }
}

并在 Global.asax 中的 Application_Start() 中注册

protected void Application_Start()
{
    /* snip */
    ViewEngines.Engines.Add(new CustomViewEngine());
}

编辑:

我这样称呼局部 View :

[HttpGet]
/// http://localhost/Account/ListUsers
/// View is located in ~/Views/Account/Partials/ListUsers.cshtml
public ActionResult ListUsers()
{
    /* populate model */

    return PartialView("ListUsers.cshtml", Model);
}

我的想法是,如果我在 View 位置中包括 Controller 参数 {1} 后跟 Partials 文件夹,这将阻止我必须对每个 Partials 子文件夹作为位置。这也意味着我可以仅通过名称而不是其完整路径来引用 View 。

但是,我仍然收到错误消息,指出在任何搜索位置都找不到局部 View 。

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

我认为指定 .chstml 扩展名是个问题,尝试在没有它的情况下返回 View :

return PartialView("ListUsers", Model);

关于c# - 在自定义 View 引擎中使用子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40249464/

相关文章:

asp.net - 如何在 Angular 路由中附加 URL?

c# - ASP.NET MVC 5 中的路由可选参数

asp.net-mvc - ASP.NET MVC View 引擎解析顺序

c# - EF Core 多对多隐藏枢轴

c# - 没有 ID 的表的复杂映射

c# - 如何从列表中选择在另一个列表/模型中没有相关对象的所有对象

Node.js - 在 Express 中从 Swig 迁移到 Nunjucks

c# - 什么是 View 引擎?它实际上做了什么?

javascript - 等号中的空格

c# - 如何在移动时忽略旋转? (在 Unity 中使用 C#)