Tags

,

A few people have posted on the SharePoint newsgroups about writing inline c# code in SharePoint 2007 masterpages. I’m certainly not saying this is a best practise, and there are many different ways to skin a cat, but if you do want to add inline c# into default.master or any other masterpage (or content layout page), these are the basic steps.

Open up SharePoint Designer and the masterpage you want to edit. Switch to the code view and anywhere from the first tag down you can add some inline c# code:

string myVar = “hello world!”;
void Page_Load(object sender, System.EventArgs e)
{
Response.Write(myVar);
SPSite siteCollection = new SPSite(“http://usb-server1”);
SPWeb site = siteCollection.OpenWeb(“/SiteDirectory/MainCalendar/”);

SPList list = site.Lists[“Announcements”];
SPListItemCollection items = list.Items;

foreach(SPListItem item in items)
{
Response.Write(item[“Title”].ToString());
Response.Write(“
“);
}

}

Doesn’t do anything amazing but does show you can use the SharePoint object model in your inline code. If you saved the masterpage now and opened the site in your browser you’d get an error about not being able to run code blocks. There’s an extra line you need to put into your web.config file first to allow this inline c# to execute.

The PageParserPaths xml tags will be there already you just need to add the line in between. Save web.config and off you go. Your pages will render properly and the c# inline code will execute.

Advertisements