Using Web Part Verbs to Shortcut Web Part Property Configuration

Web part verbs are a pretty useful yet seemingly under-utilised feature of SharePoint web parts. Over my years in SharePoint I’ve seen and created more web parts than I care to remember, yet in that time can never remember seeing one which made use of the handy functionality web part verbs provide. I’m not sure whether it’s through lack of knowledge or lack of necessity, but I thought it would be useful to highlight one scenario where harnessing web part verbs would be valid – a more efficient method of setting web part property configuration.

First though, the obligatory background information. It would be remiss of me to assume that everyone reading this knows what web part verbs are. Most however, including those who think they don’t, probably already do. They’re simply the menu items available when you click the downward arrow in the top right-hand corner of the web part chrome.

Not as many however would know that it is quite easy to get your own items into that menu. This is done by creating custom WebPartVerb objects using one of 3 constructors – one which specifies a client-side function to run in the event the action item is clicked, one which specifies a server-side function to run in the event the action item is clicked and one which specifies both a client-side and server-side function to run – and adding them to a WebPartVerbCollection. You can read about the WebPartVerb class for more information.

Now this opens up a number of possibilities – you can essentially run any code client-side or server-side from these web part verbs, however being in an environment where i’ve worked on so many public facing websites for some time now and the fact that those web parts would rarely if ever expose the web part chrome, this functionality tends to only be available when the page is in edit mode, hence lends itself to configuration actions rather than functional actions.

As such, i’ve decided to slant this post in that direction – showing how web part verbs can be used to simplify the action of configuring a web part’s properties.

Most would be familiar with the concept of web part properties. When you click the ‘Edit Web Part’ verb shown above, you make visible a tool pane in which you can set a number of web part properties. When creating a web part, you can also define custom properties which will also appear in that tool pane. Without wanting to delve into custom ToolParts or EditorParts generally web part properties are displayed based on their type – for instance a string will appear as a textbox and a boolean as a checkbox. So if I wanted to toggle a switch on my web part to enable one display type over another I would create a custom property as a boolean value and conditionally render the web part based on that value.

This is a pretty common pattern when creating generic reusable web parts and trying to minimise the sprawl of custom web parts. The example i’ll show in this post is a visual web part used for searching. The web part will have two views – a simple view and an advanced view, configurable by the user who places the web part on the page.

When simply using a custom property to achieve this, the user must click the downward arrow in the web part chrome, select Edit Web Part, expand out the relevant category, check the checkbox and click OK. It’s not ridiculously painful in SP2010 but it is a little more frustrating in SP2007. I think everyone would agree that such a simple display toggle would be better served with an option that can be selected directly from the menu which is what web part verbs enable. The example can be seen below.

Search in Simple Mode

Search in Advanced Mode

Toggling Display via the ToolPane

Toggling Display via a Web Part Verb

The code required to get this up and running is fairly simple and requires modifications to 3 files:

WebPart.cs

using Microsoft.SharePoint.WebPartPages;

namespace WebPartVerbsExample.SearchWebPart
{
    [ToolboxItemAttribute(false)]
    public class SearchWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/WebPartVerbsExample/SearchWebPart/SearchWebPartUserControl.ascx";

        [WebBrowsable(true),
        WebDisplayName("Advanced Search"),
        WebDescription("Click to show advanced options for search"),
        Personalizable(PersonalizationScope.Shared),
        Category("Custom Properties"),
        DefaultValue("")]
        public bool IsAdvancedSearch { get; set; }

        protected override void CreateChildControls()
        {
            SearchWebPartUserControl control = (SearchWebPartUserControl)Page.LoadControl(_ascxPath);
            control.IsAdvancedSearch = IsAdvancedSearch;
            Controls.Add(control);
        }

        public override WebPartVerbCollection Verbs
        {
            get
            {
                //server-side verb
                WebPartVerb titleVerb = new WebPartVerb(this.ID + "_searchModeVerb", ToggleSearchMode);
                titleVerb.Text = "Toggle Search Mode";

                // return collection with new verbs
                WebPartVerb[] verbs = new WebPartVerb[] { titleVerb };
                return new WebPartVerbCollection(verbs);
            }
        }

        // event gets executed when the user invokes the server-side verb
        void ToggleSearchMode(object sender, WebPartEventArgs e)
        {

            SPWeb site = SPContext.Current.Web;
            SPFile page = site.GetFile(Context.Request.Url.AbsolutePath);
            SPLimitedWebPartManager wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
            SearchWebPart webpart = wpm.WebParts[this.ID] as SearchWebPart;

            //Toggle the search mode
            webpart.IsAdvancedSearch = !webpart.IsAdvancedSearch;
            wpm.SaveChanges(webpart);
        }
    }
}

WebPartUserControl.ascx.cs

namespace WebPartVerbsExample.SearchWebPart
{
    public partial class SearchWebPartUserControl : UserControl
    {
        public bool IsAdvancedSearch { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

WebPartUserControl.ascx

<div>
    <% if (!IsAdvancedSearch) { %>
    <div>Search</div>
    <div>
        <!-- simple search fields -->
    </div>
    <% } else { %>
    <div>Advanced Search</div>
    <div>
        <!-- advanced search fields -->
    </div>
    <% } %>
</div>

So there you have it, a neat little way to leverage web part verbs to shortcut the need to edit the web part’s properties to set a simple configuration toggle. This makes the page editors life far easier and is definitely a more efficient way to handle such a requirement. Before I finish and on a slightly unrelated note, if you’re looking for an even more efficient way to set web part configuration values in SP2010 then check out Wictor Wilen’s post Improve the experience using Modal Dialogs when adding Web Parts in SharePoint 2010.

About these ads

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: