SharePoint 2013 - Read web part properties with client side JavaScript.
Hello,
Sometimes we want to be able to read web part properties on our client side code, e.g. when we want to use jQuery functionality to implement certain requirements.
Easiest way to achieve this is just use the asp:HiddenField control to store the value of the property, then get the value using jQuery.
So on your html:
Then on the JavaScript section:
On your ascx code behind file, just store the value during page load:
Hope this helps,
Andreas
Sometimes we want to be able to read web part properties on our client side code, e.g. when we want to use jQuery functionality to implement certain requirements.
Easiest way to achieve this is just use the asp:HiddenField control to store the value of the property, then get the value using jQuery.
So on your html:
1 | < asp:HiddenField ID = "hidMyProp" runat = "server" /> |
1 2 3 | $( function () { var myProp = $( '#' + '<%=hidMyProp.ClientID%>' ).val() != '' ? $( '#' + '<%=hidMyProp.ClientID%>' ).val() : 'default' ; }); |
On your ascx code behind file, just store the value during page load:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | [ToolboxItemAttribute( false )] public partial class MyWebPart: WebPart { [WebBrowsable( true ), WebDisplayName( "My Property" ), WebDescription( "My Web Part Custom Property" ), Personalizable(PersonalizationScope.Shared), Category( "My Custom Web Parts" )] public string MyProp { get ; set ; } public MyWebPart() { } protected override void OnInit(EventArgs e) { base .OnInit(e); InitializeControl(); } protected void Page_Load( object sender, EventArgs e) { string myProp = this .MyProp; hidMyProp.Value = myProp; } } |
Hope this helps,
Andreas
Thank you, this works perfect!
ReplyDelete