Simple check if block is in edit mode
When working with EPiServer page views there is a useful property - PageEditing.PageIsInEditMode, which allows checking if the page is open in edit mode. But when working with block views, there is no such property.
I found one solution on EPiServer Forum but I do not like it because it uses ViewBag or developer should check if the current page is a PreviewPage.
Instead, I have created extension method BlockIsInEditMode for the ViewContext.
public static class ViewContextExtensions
{
public static bool BlockIsInEditMode(this ViewContext context)
{
return IsPageController(context, "BlockPreview");
}
public static bool IsPageController(this ViewContext context, string controllerName)
{
var pageController = context.RequestContext.RouteData.Values["pagecontroller"]
?? context.RequestContext.RouteData.Values["controller"];
return pageController != null
&& pageController.ToString().Equals(controllerName, StringComparison.InvariantCultureIgnoreCase);
}
}
This method checks if current controller is block preview controller. If so, then block is in the edit mode.
As the ViewContext is available in the view, you can use it like this:
@if(ViewContext.BlockIsInEditMode())
{
@* Do some stuff here *@
}