1

In sharepoint 2013, I have a content editor web part. I have javascript code in it. I want to get a GUID. I want to get the GUID of the instance of the web part. So if I had 2 content editor webparts they should have unique identifiers each. No other content editor web part (even on another page) should have that same GUID.

I was looking at the DOM explorer in dev tools, and see on the web part there is a tag with class ms-WPBody and attribute webpartid="7722f3d5-e8da-4b3b-acc4-3bf3e6f9aba7" (for example). It seems to be different per instance of this web part on the same page too.

If I put the javascript code in the web part (linked to a file option too). I am thinking of doing something like, using jquery's nearest function to get the closest parent div.ws-WPBody and then grabbing the webpartid value.

Is this an ok way, or is there any issues or better ways?

Thanks

1 Answer 1

1

Typically when you want the ID from inside the web part, it is to ensure uniqueness in included client side script (since you might add the web part more than one time).

For this purpose, ID and ClientID works fine. If you need the GUID you could use string handling to remove the prefix.

protected override void RenderContents(HtmlTextWriter writer)
{
    base.RenderContents(writer);

    writer.Write("WebPart ID: {0}<br/>", this.ID);
    writer.Write("WebPart ClientID: {0}<br/>", this.ClientID);
}

will render similar to this:

WebPart ID: g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3 WebPart ClientID: ctl00_m_g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3

WebPart1 myWebPart = (WebPart1)this.WebPartManager.FindControl(this.ID);
writer.Write("Webpart from WPM: ID: {0}", myWebPart.ID);

Webpart from WPM: ID: g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.