Могу ли я указать настраиваемое местоположение для поиска метаданных в ASP.NET MVC?
У меня есть следующий макет для моего проекта mvc:
- /Контроллеры
- /Demo
- /Demo/DemoArea1Controller
- /Demo/DemoArea2Controller
- и т.д...
- /Просмотров
- /Demo
- /Demo/DemoArea1/Index.aspx
- /Demo/DemoArea2/Index.aspx
Однако, когда у меня есть это для DemoArea1Controller
:
public class DemoArea1Controller : Controller
{
public ActionResult Index()
{
return View();
}
}
Я получаю ошибку "Просмотр" или его мастер не удалось найти "с обычными местоположениями поиска.
Как я могу указать эти контроллеры в поиске пространства имен "Demo" в подпапке просмотра "Демо"?
Ответы
Ответ 1
Вы можете легко расширить 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;
}
}
Не забудьте зарегистрировать механизм просмотра, изменив метод Application_Start в файле Global.asax.cs
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());
}
Ответ 2
На самом деле гораздо проще, чем hardcoding пути в ваш конструктор. Ниже приведен пример расширения движка 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 в корневом каталоге.
Ответ 3
Теперь в MVC 6 вы можете реализовать интерфейс 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, добавьте следующие строки в метод ConfigureServices
в файле Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new MyViewLocationExpander());
});
}
Ответ 4
Если вы хотите просто добавить новые пути, вы можете добавить к механизмам просмотра по умолчанию и сохранить некоторые строки кода:
ViewEngines.Engines.Clear();
var razorEngine = new RazorViewEngine();
razorEngine.MasterLocationFormats = razorEngine.MasterLocationFormats
.Concat(new[] {
"~/custom/path/{0}.cshtml"
}).ToArray();
razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats
.Concat(new[] {
"~/custom/path/{1}/{0}.cshtml", // {1} = controller name
"~/custom/path/Shared/{0}.cshtml"
}).ToArray();
ViewEngines.Engines.Add(razorEngine);
То же самое относится к WebFormEngine
Ответ 5
Вместо того, чтобы подклассифицировать RazorViewEngine или заменить его прямо, вы можете просто изменить существующее свойство RazorViewEngine PartialViewLocationFormats. Этот код находится в Application_Start:
System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines
.Where(e=>e.GetType()==typeof(RazorViewEngine))
.FirstOrDefault();
string[] additionalPartialViewLocations = new[] {
"~/Views/[YourCustomPathHere]"
};
if(rve!=null)
{
rve.PartialViewLocationFormats = rve.PartialViewLocationFormats
.Union( additionalPartialViewLocations )
.ToArray();
}
Ответ 6
Последнее, что я проверил, требует, чтобы вы создали собственный ViewEngine. Я не знаю, сделали ли это проще в RC1.
Основной подход, который я использовал до первого RC, был в моем собственном ViewEngine для разделения пространства имен контроллера и поиска папок, которые соответствовали частям.
EDIT:
Вернулся и нашел код. Вот общая идея.
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName)
{
string ns = controllerContext.Controller.GetType().Namespace;
string controller = controllerContext.Controller.GetType().Name.Replace("Controller", "");
//try to find the view
string rel = "~/Views/" +
(
ns == baseControllerNamespace ? "" :
ns.Substring(baseControllerNamespace.Length + 1).Replace(".", "/") + "/"
)
+ controller;
string[] pathsToSearch = new string[]{
rel+"/"+viewName+".aspx",
rel+"/"+viewName+".ascx"
};
string viewPath = null;
foreach (var path in pathsToSearch)
{
if (this.VirtualPathProvider.FileExists(path))
{
viewPath = path;
break;
}
}
if (viewPath != null)
{
string masterPath = null;
//try find the master
if (!string.IsNullOrEmpty(masterName))
{
string[] masterPathsToSearch = new string[]{
rel+"/"+masterName+".master",
"~/Views/"+ controller +"/"+ masterName+".master",
"~/Views/Shared/"+ masterName+".master"
};
foreach (var path in masterPathsToSearch)
{
if (this.VirtualPathProvider.FileExists(path))
{
masterPath = path;
break;
}
}
}
if (string.IsNullOrEmpty(masterName) || masterPath != null)
{
return new ViewEngineResult(
this.CreateView(controllerContext, viewPath, masterPath), this);
}
}
//try default implementation
var result = base.FindView(controllerContext, viewName, masterName);
if (result.View == null)
{
//add the location searched
return new ViewEngineResult(pathsToSearch);
}
return result;
}
Ответ 7
Попробуйте что-то вроде этого:
private static void RegisterViewEngines(ICollection<IViewEngine> engines)
{
engines.Add(new WebFormViewEngine
{
MasterLocationFormats = new[] {"~/App/Views/Admin/{0}.master"},
PartialViewLocationFormats = new[] {"~/App/Views/Admin//{1}/{0}.ascx"},
ViewLocationFormats = new[] {"~/App/Views/Admin//{1}/{0}.aspx"}
});
}
protected void Application_Start()
{
RegisterViewEngines(ViewEngines.Engines);
}
Ответ 8
Примечание: для ASP.NET MVC 2 у них есть дополнительные пути к местоположению, которые вам нужно будет установить для просмотров в 'Areas'.
AreaViewLocationFormats
AreaPartialViewLocationFormats
AreaMasterLocationFormats
Создание механизма просмотра для области описано в блоге Фила.
Примечание. Это для предварительного просмотра 1, поэтому возможны изменения.