我知道在 Asp.Net 中可以为 Global.asax 中的部分 View 设置默认位置格式,并且我知道在 Asp.Net Core 中可以为类似这样的 View 设置 ViewLocationFormats:
// services is of type IServiceCollection
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorOptions(options =>
{
// {0} - Action Name
// {1} - Controller Name
// {2} - Area Name
// Replace normal view entirely
options.ViewLocationFormats.Clear();
options.ViewLocationFormats.Add("/Features/{1}/{0}.cshtml"); //Features/{Controller Name}/{Action Name}.cshtml
options.ViewLocationFormats.Add("/Features/{1}/Views/{0}.cshtml"); //Features/{Controller Name}/Views/{Action Name}.cshtml
options.ViewLocationFormats.Add("/Features/Shared/{0}.cshtml"); //Features/Shared/{Action Name}.cshtml
options.ViewLocationFormats.Add("/Features/Shared/Views/{0}.cshtml"); //Features/Shared/Views/{Action Name}.cshtml
});
对于我的生活,我不知道如何设置部分 View 的位置格式?
以下代码部分将不起作用,因为 Razor 引擎似乎无法找到部分 View :
public async Task<PartialViewResult> EntityChangeDetailModal(EntityChangeListDto entityChangeListDto)
{
var output = await _auditLogAppService.GetEntityPropertyChanges(entityChangeListDto.Id);
var viewModel = new EntityChangeDetailModalViewModel(output, entityChangeListDto);
return PartialView("_EntityChangeDetailModal", viewModel);
}
我知道我可以显式传递部分 View 的相对路径,但我更希望能够只更新默认位置,以便 Razor 引擎可以解析这些引用,而无需我对我们的内容进行大量更改现有代码库。
最佳答案
请在startup.cs中添加此代码以配置默认的部分 View
可以使用启动中的ConfigureServices方法中的Razor View 引擎选项将其他位置添加到默认注册的搜索路径(页面/共享和 View /共享)。以下代码块将 Pages/Partials 文件夹添加到搜索路径,这意味着您可以将部分文件放在那里并找到它们:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddRazorOptions(options =>
{
options.PageViewLocationFormats.Add("/Pages/Partials/{0}.cshtml");
});
}
MVC Global.asax 中的 customEngine.PartialViewLocationFormats
ViewEngines.Engines.Clear();
var customEngine = new RazorViewEngine();
customEngine.PartialViewLocationFormats = new string[]
{
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Partial/{0}.cshtml",
"~/Views/Partial/{1}/{0}.cshtml"
};
ViewEngines.Engines.Add(customEngine);
关于asp.net-mvc - Asp.Net核心2.1 : Set partial view default location formats,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656857/