Check if (partial) view exists from HtmlHelperMethod

If you are using Asp.Net Core (Mvc) you can check if "View" exists in your HtmlHelper Extension like this:

    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 ###");
     }

For completeness, the way to find a partial view, is actually as follows.

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

And be sure to include the extension of the view; either cshtml for razor or aspx for webforms view engines.


But you can't do the above in a helper, as you don't have access to the controller context.

Oh yes, you do have access:

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

Tags:

C#

Asp.Net Mvc