Creating a Dropdown menu in the Web Part Config
For web part config pages, particular data types have their own significance with how they appear on the resulting web part configuration. I needed a dropdown menu which, as I learned, requires an enum. This was simple enough:1 [WebBrowsable(true), Category("My Category"),
2 WebPartStorage(Storage.Shared),
3 WebDisplayName("Default Viewer")]
4 public ViewerType ViewerSelection
5 {
6 get 7 {
8 return viewerSelection.Value;
9 }
10 set 11 {
12 viewerSelection = value;
13 }
14 }
An explanation of the attributes:
- The WebBrowsable attribute makes this property actually show up on the form
- The Category attribute dictates the category this option will appear in
- The WebPartStorage attribute defines how this setting is shared between users. My choice of the Storage.Shared enum of the Storage Enumeration dictates that it is shared between all users and additionally that only users with contribute or greater permission can change it.
- The WebDisplayName attribute defines a title under which the property appears
Nullable backing fields
At this point you’re probably wondering what is in the enum ViewerType and why in the “get” I retrieve the enum value of the backing field and not just the enum. Here’s what it looks like:
1 public enum ViewerType
2 {
3 HTML,
4 Silverlight
5 };
6 private ViewerType? viewerSelection = null;
This was necessary because of an interesting situation where if the web part hadn’t been configured yet (first time use), it should simply use an option configured in my Service Application. I would have just made the property itself and the backing field nullable, but doing so would cause the enum to be interpreted as a string and my web part config would lose the dropdown menu functionality. Yuck. By making only the backing field nullable, I’m able to test for a null value in the constructor of the web part config and grab the appropriate value from the Service Application instead while maintaining the dropdown menu.
An enum is a value type and cannot simply be set to null like so:
1 private ViewerType viewerSelection = null;
There is no implicit conversion between an nullable enum and an enum, hence why I was required to implement the “get” on my property to retrieve the actual value from the nullable enum.
In the end, the result of this code is a dropdown menu for my web part config with a choice between two viewers. If it hasn’t been configured yet, I have the ability to test an enum for a null value and configure it appropriately. Once it’s been configured, even if you navigate away or close the browser, SharePoint will store this value and re-set it when you return!
No comments:
Post a Comment