3

In ASP.NET Core Rendering Host, I would like to hide something if the page is not in Experience Editor mode, with something like Sitecore.Context.PageMode.IsExperienceEditor in ASP.NET. Is it possible?

2 Answers 2

3

It seems that the originally accepted answer is no longer true. Adding the ISitecoreRenderingContext to DI in startup.cs as described in step 1 does allow ISitecoreRenderingContext to be injected into views/class, but it contains only NULL for all values.

Instead, inject the IHttpContextAccessor into your view/class and use the following code to get the same result:

@inject IHttpContextAccessor HttpContextAccessor
if (HttpContextAccessor.HttpContext?.GetSitecoreRenderingContext()?.Response?.Content?.Sitecore?.Context?.IsEditing ?? false)
{
    ...
}
5

It is possible by using ISitecoreRenderingContext. Although it's not a static class anymore, so you need to add to your DI container and inject it to your class and/or view.

1. Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddScoped<ISitecoreRenderingContext, SitecoreRenderingContext>();
    ...
}

2/a. In a view:

@inject ISitecoreRenderingContext SitecoreContext
if (SitecoreContext.Response?.Content?.Sitecore?.Context?.IsEditing ?? false)
{
    ...
}

2/b. in a class:

private readonly ISitecoreRenderingContext _sitecoreContext;
    
public YourClass(ISitecoreRenderingContext sitecoreContext)
{
    _sitecoreContext = sitecoreContext;
}

public void YourMethod()
{
    if (_sitecoreContext.Response?.Content?.Sitecore?.Context?.IsEditing ?? false)
    {
        ...
    }
}

If you need to distinguish between Edit/Preview/Normal then you can use SitecoreContext.Response?.Content?.Sitecore?.Context?.PageState, which represents all the 3 states.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.