Thursday, October 10, 2013

Javascript blocks in webparts not working in SharePoint 2010.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Ouch, this took me by surprise.  I have been fighting with two webparts which were migrated from 2007 to 2010.  They used some simple javascript to change div tag blocks from none to display.  They worked great in 2007 but failed in 2010. 

Issue:
Div tags and javascript functions are inserted into page where the webpart was hosted.  The onclick events would fire but not find the function references.  Thus the div tag functionality did not work in 2010.

Solution:
In the onload event changed Page.ClientScript.RegisterClientScriptBlock  to Page.ClientScript.RegisterStartupScript.

Explanation:
During the onload event of the webpart, the Page.ClientScript.RegisterClientScriptBlock was used to insert the javascript into the page.  This puts the code base at the top of the page right after the viewstate variables.  This is also where all of the 2010 ribbon controls are at.  This collision was the reason the webparts could not see the javascript blocks.  Changing the Page.ClientScript.RegisterClientScriptBlock to Page.ClientScript.RegisterStartupScript puts the script block after all the elements and right before the close form tag.

Source:
http://stackoverflow.com/questions/666519/difference-between-registerstartupscript-and-registerclientscriptblock

No comments:

Post a Comment