C# – Add general C# code to a SharePoint 2010 site page

asp.netcreferencesharepoint

I want to add a C# class to an existing SharePoint 2010 site page. The site page, being created either through the SharePoint UI or in SharePoint Designer, has a web part on it that I want to access and edit its properties. I could just make an invisible web part in Visual Studio, deploy it on the page, and run the code I want to run that way, but I feel like that may be bad practice (or is it)?

I'm kind of talking about how a general non-SharePoint .aspx page can reference a C# file, kind of like below:

<%@ Page language="C#" Inherits="System.Web.UI.Page" CodeFile="Example.cs" %>

Would a line like above be added to the .aspx file? How is the .cs file actually deployed on the SharePoint site? Finally, is this even possible?

I'm new to SharePoint and to this site, so I appreciate all help!

Best Answer

By default, SharePoint does not support code behind files in regular pages for security reasons (although, as alfonso mentioned, inline code and code behind files are supported by application pages). You can override this setting in the web.config, but that is not considered to be a good practice.

You certainly could create another web part to do what you want. I have done something similar to that before. But typically, when I want to change the behavior of a custom page, I change the Inherits attribute of the Page directive:

<%@ Page 
    language="C#" 
    DynamicMasterPageFile="~masterurl/default.master"
    Inherits="MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" 
    %>

Create your class, have it inherit from System.Web.UI.Page, then deploy it to the GAC. Not only is this supported, but this is how most of the out of the box SharePoint pages do it.

Related Topic