Friday, November 9, 2007

Functional User Control Without Codebehind class

I needed a user control without codebehind. This is because if you use codebehind, this source compiles with the dll of the web assemly and changes the inherits page directive. But I needed a user control that does not compile nieghter in the main assebly, nor in its own.

The important here is to set ClassName directive. So that's how I got it:


<%@ Control Language="C#" AutoEventWireup="true" ClassName="MyUserControl" %>

<script runat="server" type="text/C#">

public MyUserControl( string sProperty )
{
m_sProperty = sProperty;
}

private string m_sProperty;

public string Property
{
get
{
return m_sProperty;
}
set
{
m_sProperty = value;
}
}
</script>

<%= m_sProperty%>

There are two ways to use it:

1) In aspx file should be something like that:

<%@ Register TagPrefix="custom" TagName="MyUserControl" Src="~/MyUserControl.ascx" %>
...
<custom:MyUserControl runat="server" id="MyUserControl1" Property="this is a test (1)" />

2) In aspx.cs file (codebehind) should be something like that:

ASP.MyUserControl MyUserControl2 = new ASP.MyUserControl( "this is a test (2)" );
Controls.Add( MyUserControl2 );

No comments:

eXTReMe Tracker