Search This Blog

Saturday, March 18, 2017

How to update the JSLink value of a Web Part Programmatically via CSOM in Office365

    //The below Code is used to update the JSLink property value of a webpart  programmatically using csom

    using (ClientContext oClientContext = new ClientContext(siteUrl))
    {
      //Connect to the SharePoint Online site
       oClientContext.AuthenticationMode = ClientAuthenticationMode.Default;
       oClientContext.Credentials = credentials;
       oClientContext.Load(clientContext.Web);
       oClientContext.ExecuteQuery();

      //Get the list
       List olist = oClientContext.Web.Lists.GetByTitle(“Test List”);
       oClientContext.Load(olist);
       oClientContext.Load(olist.Forms);
       oClientContext.ExecuteQuery();

      //Get all the forms
       foreach (var spForm in olist.Forms)
       {
        //Get the New form
        if (spForm.ServerRelativeUrl.Contains(“NewForm.aspx”))
        {
           File oFile = oClientContext.Web.GetFileByServerRelativeUrl(spForm.ServerRelativeUrl);
           LimitedWebPartManager wpm = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
           oClientContext.Load(wpm.WebParts,wps => wps.Include(wp => wp.WebPart.Title));
           oClientContext.ExecuteQuery();

          //Set the properties for all web parts
          foreach (WebPartDefinition wpd in wpm.WebParts)
          {
            WebPart wp = wpd.WebPart;
            wp.Properties[“JSLink”] = “~/sitecollection/Style%20Library/CustomScript.js”;
            wpd.SaveWebPartChanges();
            oClientContext.ExecuteQuery();
          }
        }

      }

    }

         

No comments:

Post a Comment