Share via


How to read custom web part properties at client side using javascript in SharePoint 2010

There are some scenarios where you might need to have custom web part properties available at client side. Reading web part properties in client side can be tricky while developing a sandbox solution for SharePoint Online, where we cannot use Visual Web Parts.

Examples of such scenarios are:

  • Passing web part properties data to third party JavaScript.
  • Using web part properties to loading data on demand at client side.

Here is the approach that is followed for this solution. Please note this is not the only approach to achieve this functionality.

1. Read the required web part properties at server side

2. Format the web part properties data as JSON string, so that it can be read by javascript.

3. Create a Hidden field and assign the JSON string as its value.

4. Add javascript reference and HTML controls to the page while rendering the page (Render event). The HTML controls contains a button that, on clicking, calls a javascript function.

5. Read the JSON object from hidden field value in the javascript.

6. Use the data as per your requirement.

 

Creating Solution:

Lets start with creating a Sandbox solution in Visual Studio. It can be a farm solution also, I have chosen sandbox so that it can be deployed in SharePoint online also.

Add a "Scripts" Module and then a JavaScript file named "ReadPropertiesAtClient" in the Scripts module.

Add a simple Web Part (not a visual web part because it is a sandbox solution), named "ReadAtClientWebPart"

 Open Elemets.xml and modify it to map it to Style Library:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="https://schemas.microsoft.com/sharepoint/">
  <Module Name="Scripts" Url="Style Library/CustomScripts">
  <File Path="Scripts\ReadPropertiesAtClient.js" Url="Scripts/ReadPropertiesAtClient.js" Type="GhostableInLibrary" />
</Module>
</Elements>

 

The WebPart code:

Create two sample web part properties (WebPartName and WebPartDescription) that we will try to read.

[WebBrowsable(true)]
[WebDisplayName("Web Part Name")]
[WebDescription("Name of the WebPart")]
[Personalizable(PersonalizationScope.Shared)]
public string WebPartName { get; set; }

[WebBrowsable(true)]
[WebDisplayName("Web Part Description")]
[WebDescription("Web Part Description")]
[Personalizable(PersonalizationScope.Shared)]
public string WebPartDescription { get; set; }

Now we need to override 3 methods: CreateChildControls, OnPreRender and Render

In CreateChildControls, create a hidden field object "hiddenWebPartProperties" and add it to controls

protected override void CreateChildControls()
{
base.CreateChildControls();
HiddenField hiddenWebPartProperties = new HiddenField() { ID = "hiddenWebPartProperties" };
this.Controls.Add(hiddenWebPartProperties);
}

In OnPreRender create a JSON object of required webpart properies (WebPartName and WebPartDescription in our case).

protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            ////Construct JSON using the WebPart Properties
            string webPartPropertiesJSON = string.Empty;
            webPartPropertiesJSON = "{ 'WebPartName':'" + this.WebPartName + "', 'WebPartDescription': '"
                                                      + this.WebPartDescription + "' }";
            ((HiddenField)this.FindControl("hiddenWebPartProperties")).Value = webPartPropertiesJSON;
        }

 

Override Render to add javascript reference and HTML controls to the page. For page controls, I have added a button in a "DIV" and assigned a client click event to the button. On click of the button a javascript function "showProperties" is called that accepts SharePoint server control ID. 

protected override void Render(HtmlTextWriter writer)
        {
            this.RenderContents(writer);

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.AddAttribute(HtmlTextWriterAttribute.Src,
                                            string.Format("{0}/Style Library/CustomScripts/Scripts/ReadPropertiesAtClient.js",
                                            SPContext.Current.Site.ServerRelativeUrl.TrimEnd('/')));
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.RenderEndTag();

            writer.Write("<div id='webPartDiv' style='align:center; margin:3px; border: solid thin black;" +
                               "width: 400px; height: 200px'>"+
                               "<input type=\"button\" value=\"Click to see web part properties\""+
                               " onclick=\"showProperties('"+this.ClientID+"')\"/>"+"</div>");
        }

The JavaScript code:

JavaScript code is very simple it has a function to show the properties on client side. Add below function to "ReadPropertiesAtClient.js" file.

    function showProperties(clientID) {
        var hiddenField = document.getElementById(clientID + '_hiddenWebPartProperties');
        if (hiddenField != undefined && hiddenField != null) {
            webpartProperies = eval("(" + hiddenField.value + ")");
        }
        var properties = "WebPart Name: " + webpartProperies.WebPartName + ". WebPart Description: " + webpartProperies.WebPartDescription;
        alert(properties);
    }

 

Deploy and Run:

Now the coding part is done, all we need to do is deploy the solution and add the webpart to a page.

Edit the web part and assign the value to the custom webpart properties, click 'Apply' and 'OK'. Now Click on 'Save and Close' button on the ribbon.

The page is ready, now we can test our webpart. Click the button and the webpart properties are displayed in an alert box.

Comments

  • Anonymous
    August 17, 2015
    Thanks bhai,.. It's very helpful,...

  • Anonymous
    November 25, 2015
    Hey , You save my lot of time .It is really a good work