May
6
2008

Using ASP.NET Web User Control with Code Behind in SharePoint

What are we trying to do?

Let's say you want to create an ASP.NET page in SharePoint site. HelloWorld.aspx and put it in ~site/_layouts/HelloWorld.aspx.

In this HelloWorld.aspx page, you have some Web User Controls (.ascx) that provide different functions to user when they view this page. And each Web User Control has its code behind file (.ascx.cs)

How can you do this in SharePoint?

First of all, you have to understand where those files should live in file system hierarchy.

HelloWorld.aspx - 12\TEMPLATE\LAYOUTS\

WebUserControl1.ascx - 12\TEMPLATE\CONTROLTEMPLATES

WebUserControl2.ascx - 12\TEMPLATE\CONTROLTEMPLATES

WebUserControl1.ascx.cs - compiled as .dll and put in GAC

WebUserControl2.ascx.cs - GAC

As you can see unlike normal ASP.NET web site where .ascx and .ascx.cs store under same folder and will get complied at runtime. In SharePoint there is no concept of code behind but assembly references.

How to do it?

Step 1. Register Web User Controls In HelloWorld.aspx. Just like how normal ASP.NET page would do for Web User Controls.


<!--HelloWorld.aspx - register web user control and use it -->

<%@ Register src="~/_controltemplates/WebUserControl1.ascx" TagName="WebUserControl1" TagPrefix="ucWebUserControl1" %>

<ucWebUserControl1:WebUserControl1 ID="myWebUserControl11" runat="server" />

 

 

Step 2. Create a new class project with all your code behind class files (.ascx.cs)

//WebUserControl1.ascx.cs

namespace JamesTsai.Net.UserControls

{

    public partial class WebUserControl1 : System.Web.UI.UserControl

    {

        protected TextBox txtBox1;

        protected void Page_Load(object sender, EventArgs e)

        {

             txtBox1.Text = "hello world";

        }

    }

}

Compile this project with strong name (signing with key). MAKE sure this .dll is copied to GAC

In this example JamesTsai.Net.UserControls.dll will contains infomation like

"JamesTsai.Net.UserControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30dc9c27cebc6002"

 

Step 3. Create Web User Control (.ascx)

The Web User Control will look like


<%@ Assembly Name ="JamesTsai.Net.UserControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30dc9c27cebc6002"%>


<%@ Control Language="C#" AutoEventWireup="false" Inherits="JamesTsai.Net.UserControls.WebUserControl1" %>


<!-- you can use textbox we declared in code behind like this -->


<asp:TextBox id="txtBox1" runat="server" Text="" />

 

Step 4. View your page

After you deployed above files you can view your page in

http://yoursite/_layouts/HelloWorld.aspx

And hopefully you can also see a textbox with text "hello world" inside. If you have more than one Web User Controls, just repeat steps 1 to 3 above.

 

blog comments powered by Disqus