Friday, August 7, 2015

How to dynamically hide web part in Sharepoint so it won’t take place on a page

Suppose that we have visual web part which shows some items (e.g. news). If there are no items to show we want this web part to not take any place on the page. Unfortunately by default Sharepoint reserves some place for empty web parts even if they have Chrome type set to None. In some cases it will cause layout to not look very well. Using the following trick we may hide web part completely:

   1: public class NewsControl : UserControl
   2: {
   3:     protected Repeater rpt;
   5:     protected override void OnLoad(EventArgs e)
   6:     {
   7:         var news = this.getNews();
   8:         if (news.IsNullOrEmpty())
   9:         {
  10:             if (SPContext.Current.FormContext.FormMode != SPControlMode.Edit)
  11:             {
  12:                 this.hideParentWebPart();
  13:             }
  14:             return;
  15:         }
  16:         this.rpt.DataSource = news;
  17:         this.rpt.DataBind();
  18:     }
  20:     // hide web part so it won't take any place on the page
  21:     private void hideParentWebPart()
  22:     {
  23:         string script =
  24:             string.Format("try {{ jQuery(\"td[id$='{0}']\").hide(); }} catch(e){{}}",
  25:                 this.Parent.ID);
  26:         this.Page.ClientScript.RegisterStartupScript(GetType(), "Notifications",
  27:             script, true);
  28:     }
  30:     private List<News> getNews()
  31:     {
  32:         ...
  33:     }
  34: }

In our example we assume that web part loads NewsControl to its child controls and don’t have any other logic. So inside control we need to hide parent web part. We do it by injecting javascript code when there are no news to show (lines 21-28). This trick is based on the knowledge that Sharepoint renders td element for web part (if in further versions it will render other html elements, just change td on appropriate element) which id ends with web part id. We find this td using jQuery and hide it:


One additional thing to mention is that we do it when page is not in edit mode (line 10). Otherwise it won’t be possible to edit or delete web part from the page.

No comments:

Post a Comment