为了在我的新 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/