Thursday, July 22, 2010

Write C# code in aspx form

Quote from Nick's blog

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

<script runat="server">
string myVar = "hello world!";
void Page_Load(object sender, System.EventArgs e)
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)


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.

<PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />

No comments:

Post a Comment