Today I came across one of the scenario where i need to check page is in edit mode or not.
Scenario: We have sharepoint custom webpart which needs to be cached. Problem here was if the user update the any of the webpart property it was not reflecting automatically(another way we can achieve this was using webpart tool property)
Because, in the create child control method we are checking whether the control is cached or not, since the webpart was available in the cache this was not rebuilding the control.
So solution for this problem is if page is in edit mode then rebuild the webpart else check if the webpart is available in the cache if it is available then get it from there else rebuild the control.
//The below code will work if we are using pages which are associated to page layout
Scenario: We have sharepoint custom webpart which needs to be cached. Problem here was if the user update the any of the webpart property it was not reflecting automatically(another way we can achieve this was using webpart tool property)
Because, in the create child control method we are checking whether the control is cached or not, since the webpart was available in the cache this was not rebuilding the control.
So solution for this problem is if page is in edit mode then rebuild the webpart else check if the webpart is available in the cache if it is available then get it from there else rebuild the control.
//The below code will work if we are using pages which are associated to page layout
if(Microsoft.SharePoint.SPContext.Current.FormContext.FormMode = SPControlMode.Edit)
{
//Page is in edit mode
BuildTheWebpart();
}
else
{
//Page is in display mode
if(WebpartIsAvailableInCache())
{
//Get the webpart from cache and render it
}
else
{
BuildTheWebpart();
}
}
What about if it is simple webpart page?
WebPartManager wpManager =
this
.WebPartManager;
if
(wpManager.DisplayMode == WebPartManager.EditDisplayMode)
{
//This indicated page is in edit mode
BuildTheWebPart();
}
else
{
//Page is in display mode
if(WebpartIsAvailableInCache())
{
//Get the webpart from cache and render it
}
else
{
BuildTheWebpart();
}
}
But none of the above code didn't solve my problem. The page was provisioned through feature and its not associated to any page layout it just provisioned in the page library.
The simplest fix i found out is check page is checked out or not
Usually for all sharepoint sites this will be activated by administrator so we can use this to check page is in edit mode or not
if(Microsoft.SharePoint.SPContext.Current.FileLevel = SPFileLevel.CheckOut)
{
//Edit mode
Build the control
}
else
{
//page is checked in so user is not updating any of the webpart property
}
Hopefully if any one face the issue like me can use this check to determine page is in edit or not.