Monday 10 December 2012

Read web part properties with javascript

The scenario: You have a visual web part with one or more properties you need to read from some javascript code related to the web part.

One way to do this, is to add a hidden html input control (with runat=server set) to the user control.
In the code behind for the user control assign the value of the property to the input element like this:



        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (this.WebPart != null)
            {
                wsurl.Value = WebPart.ValidationWebServiceUrl;
            }
        }

In the code above "wsurl" is the id of my hidden html input control, and "ValidationWebServiceUrl" is the property on my web part.

Voila - now you can read the value of the input element containing the property value from javascript. :-)