SharePoint 2010 – More on Web Parts

In this article we can explore more features regarding Web Parts programming.

Images Mapped Folder

In real world scenario we need to locate an image file from the server web folder. We can use the Server.MapPath() pointing to the root (~). But this is not that easy with web parts as the web parts are not always deployed into the bin folder.

(While development the web part assembly is not placed inside the inetput folder)

We can deploy web part to Solution Gallery, Global Assembly Cache and the web application bin directory. For simplicity we can use the Images Mapped Folder to place the image files needed by the web part.

Creating Image File Loading Project

Now we can create a web part and experiment the image loading functionality. Create a new SharePoint > 2010 > Visual Web Part project.

clip_image002

Select the SharePoint default web site in the next dialog.

Create Images Mapped Folder

For adding image files we need to use a special mapped folder. Right click on the project and use the SharePoint Images Mapped Folder from the Add menu.

clip_image004

Copy an Image File inside the Folder

Now create an image file and paste inside the folder.

clip_image006

Create Image control to load the Image File

Double click to open the VisualWebPart1UserControl.asx.

clip_image008

Now place a button and image control on the web part user control.

On the button click event place the following code :

protected void Button1_Click(object sender, EventArgs e)

{

Image1.ImageUrl = "/_layouts/images/ImageFileInWebPart/Jellyfish.jpg";

}

Please note that the url starts with _layouts folder.

Execute the Web Part

Now you can execute the web part and it will get deployed to the site. Open a page in edit mode and use the Add Web Part option. Locate our new web part and add it to the page.

Try playing with the button click and you will be getting the image file displayed as shown below:

clip_image010

References

http://rtmgroupq8.com/en/add-image-to-sharepoint-visual-web-part

http://msdn.microsoft.com/en-us/library/cc768621.aspx

Summary

In this article we have explored more features regarding Web Parts. The Images mapping is an essential feature and will take extra time in real world development scenarios if we does not grasp the feature. The source code attached contains the examples we discussed.

Leave a Reply

Your email address will not be published. Required fields are marked *