I created my first web part connection the other day and was surprised at how easy and effective it was. I thought I would walk through the process that is required to connect two custom web parts together.
In this brief tutorial I am not going to cover how to create a web part or how to deploy one. I will assume that you (the reader) already knows how to do this. All code in this tutorial will be written in C#.
1. To begin create yourself two web parts – one of these will be the ‘Provider’ and the other the ‘Consumer’. You can create these however you like either using the VseWSS extensions or perhaps in an empty class library project.
2. Create an interface similar to the one below –
public interface IExampleProvider
{
String TestParam { get; }
}
Inside this interface you should define any parameters that you wish to send to your ‘Consumer’ web part.
3. In your Provider web part ensure that it implements the interface you have just created –
public class ProviderWebPart: WebPart, IGovernanceProvider
{
}
4. Next create a property that returns the interface and decorate it with the ConnectionProvider attribute. The parameters of are the display name and the real name (ID) of the connection.
[ConnectionProvider("Test Parameter","ExampleID", AllowsMultipleConnections=true)]
public IExampleProvider GetExampleProvider()
{
return this;
}
5. Finally for the Provider web part you need to ensure that the parameter property from your interface is implemented –
protected string _TestParam = "";
public string TestParam
{
get { return _TestParam; }
}
6. Now its time to setup the Consumer web part, in your consumer web part class define a method that will accept the interface as a parameter and decorate it with the ConnectionConsumer attribute.
private IExampleProvider exampleProvider;
[ConnectionConsumer("Site URL")]
public void RegisterProvider(IExampleProvider provider)
{
this.exampleProvider = provider;
}
7. You can now retrieve the value/values that have been sent to the consumer web part by calling the properties of the exampleProvider. Note you should check if a connection has been made first by seeing if the exampleProvider is null.
string myParam = this.exampleProvider.TestParam;
8. Deploy your two web parts by whatever method you wish, when you add the web parts to the page and click the ‘edit’ dropdown you should see a new menu option called ‘Connections’. The menu will appear on both the provider and consumer web parts but you only need to configure one.
Consumer Web Part:
Provider Web Part:
9. You are finished!
I hope you enjoyed this brief tutorial into web part connections, if you have any questions then feel free to leave a comment!
Hope this helps 🙂