我的mvc项目有以下布局:
的
的
但是,当我为DemoArea1Controller
设置了以下代码时
public class DemoArea1Controller : Controller
{
public ActionResult Index()
{
return View();
}
}
在通常的搜索位置中,我得到了"The view 'index‘or its master not be found“错误。
如何指定"Demo“命名空间中控制器在"Demo”查看器子文件夹中进行搜索?
发布于 2009-05-26 08:30:22
您可以轻松地扩展WebFormViewEngine以指定要查找的所有位置:
public class CustomViewEngine : WebFormViewEngine
{
public CustomViewEngine()
{
var viewLocations = new[] {
"~/Views/{1}/{0}.aspx",
"~/Views/{1}/{0}.ascx",
"~/Views/Shared/{0}.aspx",
"~/Views/Shared/{0}.ascx",
"~/AnotherPath/Views/{0}.ascx"
// etc
};
this.PartialViewLocationFormats = viewLocations;
this.ViewLocationFormats = viewLocations;
}
}
确保您记得通过修改Global.asax.cs中的Application_Start方法来注册视图引擎
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());
}
发布于 2015-06-19 04:09:23
现在,在MVC6中,您可以实现IViewLocationExpander
接口,而不会影响视图引擎:
public class MyViewLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context) {}
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
return new[]
{
"/AnotherPath/Views/{1}/{0}.cshtml",
"/AnotherPath/Views/Shared/{0}.cshtml"
}; // add `.Union(viewLocations)` to add default locations
}
}
其中{0}
是目标视图名称、{1}
控制器名称和{2}
区域名称。
您可以返回自己的位置列表,将其与默认viewLocations
合并(.Union(viewLocations)
)或直接更改它们(viewLocations.Select(path => "/AnotherPath" + path)
)。
要在MVC中注册您的自定义视图位置扩展器,请在Startup.cs
文件的ConfigureServices
方法中添加以下行:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new MyViewLocationExpander());
});
}
发布于 2011-09-26 23:15:20
实际上,与将路径硬编码到构造函数中相比,有更简单的方法。下面是扩展Razor引擎以添加新路径的示例。有一件事我不太确定,那就是你在这里添加的路径是否会被缓存:
public class ExtendedRazorViewEngine : RazorViewEngine
{
public void AddViewLocationFormat(string paths)
{
List<string> existingPaths = new List<string>(ViewLocationFormats);
existingPaths.Add(paths);
ViewLocationFormats = existingPaths.ToArray();
}
public void AddPartialViewLocationFormat(string paths)
{
List<string> existingPaths = new List<string>(PartialViewLocationFormats);
existingPaths.Add(paths);
PartialViewLocationFormats = existingPaths.ToArray();
}
}
和你的Global.asax.cs
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ExtendedRazorViewEngine engine = new ExtendedRazorViewEngine();
engine.AddViewLocationFormat("~/MyThemes/{1}/{0}.cshtml");
engine.AddViewLocationFormat("~/MyThemes/{1}/{0}.vbhtml");
// Add a shared location too, as the lines above are controller specific
engine.AddPartialViewLocationFormat("~/MyThemes/{0}.cshtml");
engine.AddPartialViewLocationFormat("~/MyThemes/{0}.vbhtml");
ViewEngines.Engines.Add(engine);
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
需要注意的一件事是:您的自定义位置需要根目录中的ViewStart.cshtml文件。
https://stackoverflow.com/questions/632964
复制相似问题