[英]How to check if a view exist in shared folder in ASP.NET Core MVC?
How to know view exists in ASP.NET Core? 如何知道ASP.NET Core中是否存在视图?
I'm searching for a pseudo-code like this: 我正在搜索这样的伪代码:
@if (Exists("/Views/Shared/SomeView.cshtml"))
{
Html.Partial("/Views/Shared/SomeView.cshtml"))
}
You can use FindView for this. 您可以为此使用FindView 。 Inside of a view, you can use dependency injection to get an instance of ICompositeViewEngine
, which is registered for you when adding the MVC services. 在视图内部,可以使用依赖注入来获取ICompositeViewEngine
的实例,该实例在添加MVC服务时已为您注册。 Using this instance, it's possible to determine whether or not the view exists using something like the following: 使用此实例,可以使用以下类似方法确定视图是否存在:
@inject ICompositeViewEngine Engine
@if (Engine.FindView(ViewContext, "SomeView", isMainPage: false).Success)
{
@Html.Partial("SomeView");
}
If you specifically want to check whether or not the View exists in a specific folder (eg Shared in your example), you can use GetView
: 如果您特别想检查视图是否在特定文件夹中(例如,示例中为“共享”),则可以使用GetView
:
@if (Engine.GetView(null, "Views/Shared/SomeView.cshtml", isMainPage: false).Success)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.