When you are developing custom SharePoint web parts using SharePoint Object Model, it’s not enough that you can properly render contents in “Browse mode”. Your web part must also take into account when the page it is attached to goes into “Edit mode”. In this blog post, I enumerate the different states the web part can be in in any given time. Sometimes, you would want to limit the functionality of the web part when it is not in “Browse mode”. And this is why you check what state the part is in before rendering contents for it.
You must also take into consideration the following use-cases that your web part will participate in:
- From the site’s Web Part Gallery, clicking the web part and rendering it in “Preview mode”.
- When editing the page that has the web part in SharePoint Designer 2010, that the web part renders properly as a user-control.
I want to focus on properly rendering the Web part in SharePoint Designer because this is a use-case that can be commonly missed. Today, I was testing a web part I am developing for Zenpo Software Innovations when I encountered the following error in SharePoint Designer 2010:

“Error Creating Control” – what does that mean?
The web part’s OnLoad and OnInit event-handlers didn’t check that the page is in “design mode”. So, it tried to render its content as if it was in browse-mode.
The web part uses custom JavaScript. I have to register the scripts in order for the web part to use them. I implement the script-registration during the OnInit event of the web part like the following:
protected override void OnInit(EventArgs e)
{
if (!Page.ClientScript.IsClientScriptIncludeRegistered("Script1"))
{
scriptRegistered = false;
Page.ClientScript.RegisterClientScriptInclude("Script1",
Page.ClientScript.GetWebResourceUrl(this.GetType(),
"Zenposoft.Script1.js"));
}
}
This script registration code works fine on the web browser. The problem is when this code is invoked during SPD-editing of the web part page, Page.ClientScript.GetWebResourceUrl returns empty string (under normal browsing state, it would have returned the URL to the WebResource.axd file). And you cannot pass an empty string URL to the Page.ClientScript.RegisterClientScriptInclude method (it will throw an exception if you pass an empty URL). The web part really had no business trying to register scripts during design-time.
You might say to yourself, “this shouldn’t be an issue since Web part pages are edited through the browser anyway”. Think again! Web designers at your organization will use SharePoint Designer at some point to edit SharePoint pages and if your web part cannot handle “design mode” correctly, the designers will see the ugly “Error Creating Control” in SPD. You cannot instill confidence in the use of your web part if it’s throwing exceptions in SharePoint Designer!!!
So, how do we fix this? You can use the one of the following or both:
I found this Microsoft SharePoint Designer Team Blog post that has nice explanation on how to create “designer friendly controls”. SPContext.Current.IsDesignTime and Control.DesignMode are mentioned in that blog post.
First, I modify the OnInit event-handler such that I register scripts only when “not in design mode”:
protected override void OnInit(EventArgs e)
{
if (!this.DesignMode && !SPContext.Current.IsDesignTime)
{
if (!Page.ClientScript.IsClientScriptIncludeRegistered("Script1"))
{
scriptRegistered = false;
Page.ClientScript.RegisterClientScriptInclude("Script1",
Page.ClientScript.GetWebResourceUrl(this.GetType(),
"Zenposoft.Script1.js"));
}
}
}
After deploying the modified Web part, we check SharePoint Designer and the errors are gone:

SharePoint Designer Errors - Gone
Yes, the errors are gone but we need to display something where the web part(s) are embedded. If the web part in on the page, the designer should render something there; it can’t be just white-space.
In order to render something in “design mode”, we override the Render method of the web part:
protected override void Render(HtmlTextWriter writer)
{
if (this.DesignMode || SPContext.Current.IsDesignTime)
{
writer.Write("<input type="button" value="Web part is in edit mode..." />");
}
else
{
base.Render(writer);
}
}
If the web part is in “design mode”, we render a simple HTML button. Otherwise, we let the base class (WebPart) handle the rendering. Deploy the updated web part and you should now see the following in SharePoint Designer:

Render HTML button in Desing Mode
To summarize, you will want to render web parts correctly in designers such as SPD 2010. The likelihood that Web designers will edit SharePoint pages in SPD is high enough that you will want to “design mode” for your web part to run properly.
Posted by: Gabe Hilado in
SharePoint on July 9th, 2011
Back in SharePoint 2007, it was pretty popular to use the built-in Javascript function MSOTlPn_ShowToolPane2Wrapper to put the Web part page into edit mode and have the Web part properties editable. Typically, you would put something like the following in your Web part class code:
protected override void OnPreRender(EventArgs e)
{
if (this.Page != null)
{
if (string.IsNullOrEmpty(SelectedListName))
{
placeHolderLiteral.Text = "
Web part is not configured. Please <a href="\"javascript:MSOTlPn_ShowToolPane2Wrapper('Edit',">edit the Web part</a> and choose a list or library.
";
}
}
}
In the example above, I render a “please configure the Web part” message whenever the SelectedListName of the Web part is not set.
I’m currently developing a Web part for SharePoint 2010 and I wanted to have a “configure” link displayed for the Web part whenever Web properties (i.e. list name, view ID etc.) are not set or specified . I embed a code similar to the above snippet where I use MSOTlPn_ShowToolPane2Wrapper. It didn’t work!
So, thinking like a developer, I observe how the out-of-the-box Web parts render an “open tool pane” hyperlink. I add an Image Viewer web part to a web part page and look at the structure of the hyperlink. Here’s what I saw:

I replaced my output code in my web part class from MSOTlPn_ShowToolPane2Wrapper to ShowToolPane2Wrapper and it works!
Please note that I encourage that you put ‘this’ (object) as the second argument instead of ’129′, or ’16′ as you see in some blogs out there. The second parameter is supposed to indicate which Web part to edit. Do you really know at run-time that your Web part is ’129′ or ’16′? You don’t! So simply use ‘this’.
In my previous post, I talked about input-masking to help ensure the quality of the inputs from the user. Information such as phone numbers and ZIP code can be masked because format is anticipated well in advanced. There are certain types of inputs though that are tough or impossible to mask. Take the email address for example: masking is not applicable (or cumbersome) to implement because there are so many formats that you can apply to an email address, the lengths are variable, and some special characters can be inserted anywhere before the @ sign.
Some classes of data are best validated using regular expressions (or regex). Email address is typically validated using regex. Another field or data-element similar to email address in the way you validate it is the URL (Web sites, etc.)
The OOTB SharePoint forms for the lists (NewForm.aspx and EditForm.aspx) will validate many things. For example, you can make a field be a required field and the OOTB forms will make sure the user input something. Also, when you specify a SharePoint column to be of type “something other than text” (types such “Numbers” and “Dates”) SharePoint will enforce validations on those fields as well. What’s the problem with email addresses and URLs in OOTB SP forms? They are treated as text and the values’ correctness are not enforced. Here’s an example:

An invalid email address allowed to be saved in SharePoint
You can type in “asdf” on the email address field and it will be okay for the form. That’s not right! So let’s “tweak” the SharePoint forms to make them validate email address.
For this solution, we again use jQuery JavaScript library like the input-masking exercise. We will also need the validation plugin. Upload the validation plug-in into a “scripts” library in your SharePoint site.
Next, open-up the SharePoint Site and edit the list’s NewForm.aspx or EditForm.aspx in SharePoint Designer. In this example, we are editing the Contacts List EditForm.aspx. You want to look for the table element whose ID is onetIDListForm. Insert the following code just below the table.onetIDListForm element (notice that we’re simply extending the source code from the previous post):
<script src="../../scripts/jquery-1.3.2.js"></script>
<!-- jquery plugin for input-masking... -->
<script src="../../scripts/jquery.maskedinput-1.2.2.min.js"></script>
<!-- jquery plugin for validation... -->
<script src="../../scripts/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Apply input-masks to "phone number" fields and ZIP
$("input[title='Business Phone']").mask("(999) 999-9999");
$("input[title='Home Phone']").mask("(999) 999-9999");
$("input[title='Mobile Phone']").mask("(999) 999-9999");
$("input[title='ZIP/Postal Code']").mask("99999");
/*--- Lines from this point onwards: validation of the email address field ---*/
// Apply the "validation plugin"
$("#aspnetForm").validate({
submitHandler: function(form) {
}
});
// Since it's hard to match input/field by ID value, use the validation plugin's "rules()" method
// Here, we apply the "email rule" to the input whose title is "E-mail Address"
$("input[title='E-mail Address']").rules(
"add",
{ email: true,
messages: {
email: "Please enter a valid email address."
}
}
);
// We add jquery's blur() event to the email-address field so that the form
// will keep the focus on the field until the user has corrected the problem
$("input[title='E-mail Address']").blur(function() {
if (!$("input[title='E-mail Address']").valid()) {
this.focus();
}
});
// Finally, prevent the user from clicking OK if the email address is invalid
$("input[value='OK']").focus(function(){
if (!$("input[title='E-mail Address']").valid()) {
alert("Please enter a valid email address.");
$("input[title='E-mail Address']").focus();
}
});
});
</script>
After the code snippet is inserted into the form, the SharePoint Contact form will now ensure that the inputs conform to the email address field:

Email address now validated