SharePoint Web Parts – JavaScript Support

So I’ve been tasked with developing some stuff at work for SharePoint, and so far I feel like I’m missing something fairly basic.

I bought and worked through the book ‘SharePoint 2007 Development Unleashed’ by Hoffman and Foster which was a good introductory read and certainly got me up and running. But I still feel that there must be an easier way of doing this stuff.

I’m basically creating the web part to display information by overriding the CreateChildControls() method and entry the creation of HTML controls in there, e.g.

public class MyWebPart : WebPart
{

    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        Button testButton = new Button();
        testButton.Text = "Test";
        testButton.Attributes.Add("onclick", "javascript:test();return false;");
        Controls.Add(testButton);

    }
}

Which is working fine, but is there an easier way to do this? i.e. some graphical drag-and-drop option.

You can also see from that code there I needed to handle adding JavaScript functionality. I know there is a better way of doing this via linking to the JavaScript file in the _wpresources directory for the Web Part (I’ll blog about that once I implement it properly in a week or so…). However the quickest and dirtest of way of getting it working was to override the Render(HtmlTextWriter writer) method, e.g.


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

    writer.Write("<script language='JavaScript'>");
    writer.Write("function test() { alert('Hello from test()'); }");

}

Interested to hear from other SharePoint developers on things I’m doing wrong, and in particularly any good starting guides out there!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s