tryandcatch.net

Blogs from tryandcatch.net
Welcome to tryandcatch.net Sign in | Join | Help
in Search

Ezequiel EspĂ­ndola's Blog

ASP.NET 2.0 Simplified Code Behind Model

I knew about the existence of partial classes although I haven't read much about them. It seems I will be using them a lot because ASP.NET 2.0 has the code-behind model simplified by its use.

The advantage is that you don't need to declare in the code-behind class the variables for the server controls lying on the page markup. Remember all those protected variable declarations for the 100th server controls you have on your page filling up the entire screen on the code-behind class? No need for them anymore. =)

Now you can access the server controls directly from the code-behind class just by using the CodeFile and Inherits attributes in the <%@ Page %> directive:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>My Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="MyLabel" runat="server"></asp:Label></div>
    </form>
</body>
</html>

And having your code-behind class declared as a partial class:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MyLabel.Text = "Hello ASP.NET 2.0!";
    }
}

You even get Intellisense everywhere while using VS.NET 2005. You'll get all the methods and properties for the MyLabel control on the code-behind class without even declaring that this is the partial class for the page file that has the actual Label markup. It's kind of magic! Well, actually it's the other way around (the page file declaring which class file has the code-behind) and VS.NET 2005 must know it. But, anyway...

I don't know why is the Inherits attribute needed if this is the same class sliced in pieces. I have to read more about partial classes.

Published Tuesday, December 06, 2005 1:45 PM by eespindola
Filed Under: , , ,
Anonymous comments are disabled

This Blog

Post Calendar

<December 2005>
SuMoTuWeThFrSa
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

Syndication

Powered by Community Server, by Telligent Systems