Search code examples
asp.net-core-mvcasp.net-core-2.2.net-core-2.2

How to know if IRazorPage is a partial view in IRazorPageActivator.Activate


Is there anyway to identify if the IRazorPage is a main page, a partial or the actual layout in a custom IRazorPageActivator?

The only object you have is the IRazorPage and ViewContext and I've searched alot but can't find any clues to the above info...


Solution

  • Think I actually found a solution, but not sure if it's "hacky" or not :) Im using the UrlHelpers ViewContext that will be the parent ViewContext and possible to compare ExecutingFilePath with context.View.Path that will only be equal for the actual page (not partials) and therefor possible to filter out partials!

    Needs more testing...

    public void Activate(IRazorPage page, ViewContext context)
    {
        ViewContext viewContext = null;
    
        if(context.HttpContext.Items.TryGetValue(typeof(IUrlHelper), out var urlHelper) && urlHelper is IUrlHelper)
        {
            viewContext = (ViewContext)((IUrlHelper)urlHelper).ActionContext;
        }
    
        viewContext = viewContext ?? context;
    
        // Will only set Layout for the actual page view and only if not allready set
        if(viewContext.ExecutingFilePath.Equals(context.View.Path, StringComparison.OrdinalIgnoreCase) && page.Layout == null)
        {
            page.Layout = "_SpecialLayout";
        }
    }