29

Does anyone know if it's possible to check if a partial view exists from within an HtmlHelperExtension?

I know it's possible from a controller using the following:

 private bool ViewExists(string name)
 {
     ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
     return (result.View != null);
 }

Source: Does a View Exist in Asp.Net MVC?

But you can't do the above in a helper, as you don't have access to the controller context. Any thoughts on how to do this?

4

3 回答 3

34

但是您不能在帮助程序中执行上述操作,因为您无权访问控制器上下文。

哦,是的,您确实可以访问:

public static HtmlString MyHelper(this HtmlHelper html)
{
    var controllerContext = html.ViewContext.Controller.ControllerContext;
    var result = ViewEngines.Engines.FindView(controllerContext, name, null);
    ...
}
于 2013-04-25T10:17:00.413 回答
10

为了完整起见,找到局部视图的方法实际上如下。

public static HtmlString MyHelper(this HtmlHelper html)
{
     var controllerContext = html.ViewContext.Controller.ControllerContext;
     ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, name);
     ...
}

并确保包括视图的扩展;剃须刀的 cshtml 或 webforms 视图引擎的 aspx。

于 2013-04-25T15:19:48.697 回答
1

如果您使用的是 Asp.Net Core (Mvc),您可以检查 HtmlHelper 扩展中是否存在“视图”,如下所示:

    public static IHtmlContent PartialOzz<TModel>(IHtmlHelper<TModel> htmlHelper, partialViewName)
    {
        var requestServices = htmlHelper.ViewContext.HttpContext.RequestServices;
        var viewEngine = requestServices.GetService<ICompositeViewEngine>();

        var viewEngineResult = viewEngine.GetView(htmlHelper.ViewContext.ExecutingFilePath, partialViewName, isMainPage: false);
        if (viewEngineResult.Success)
            return htmlHelper.PartialAsync(partialViewName, me.Model).Result;

        viewEngineResult = viewEngine.FindView(htmlHelper.ViewContext, partialViewName, isMainPage: false);
        if (viewEngineResult.Success)
            return htmlHelper.PartialAsync(partialViewName, me.Model).Result;

        
        return new HtmlString($"### {partialViewName} Not Found ###");
     }
于 2020-12-16T12:11:06.013 回答