Fixing the HTML that InsertWebPartIntoWikiPage generates

By on August 9, 2011,

Buried deep in the recess of the WebPartPages class, there is a static method that belongs to the WikiEditPage class and its sole purpose is to allow you to insert WebParts into a wiki page.

The static method Microsoft.SharePoint.WebPartPages.WikiEditPage.InsertWebPartIntoWikiPage basically takes 3 parameters – the file, the webpart, and the text position of where you want to inject the web part.

All is fine and dandy except for one thing – the html that is produced by the method is invalid.  The method basically injects the html shown on the slide below. 

image

Take special note of the next to last <div> tag. 

Self-closing tag results in broken wiki page!

<div style=’display:none’ id="vid_{0}"/>

The tag as written is self-closing.  Unfortunately, when the text is processed by SharePoint’s parser, the self-closing notation is not recognized as valid html and the parser leaves this tag open.  This results in a very broken wiki page because the closing </div> does not exist for the segment of html that was just injected into the page.  Take a look at the image below – 3 start tags but only 2 end tags.

image

The fix is pretty easy.  Create your own version of InsertWebPartIntoWikiPage! 

All you need to do is change that next to last div tag from one that uses the self-closing notation over to one that properly uses an end tag.

image

Once you do this, your html segment will look like…

image

Nice and clean with the right number of start and end tags. More importantly, your wiki page will work as expected.

Later this week, I’ll show you a really cool way to use regex to control the location of the web parts that you’re trying to add to the wiki page.

-Maurice

Tags , ,