다음을 통해 공유


웹 컨트롤 컬렉션 속성 예제

업데이트: 2007년 11월

이 예제에서는 컬렉션 속성에 대해 페이지에서 지속성을 구현하는 QuickContacts 컨트롤을 만드는 방법을 보여 줍니다. 페이지 개발자는 이 예제 컨트롤을 사용하여 주소록 연락처 목록을 저장할 수 있습니다. QuickContacts 컨트롤은 Contact 개체를 포함하는 Contacts 컬렉션 속성을 노출합니다. Contact 클래스에는 Name, Email 및 Phone 속성이 포함되어 있습니다.

다음 예제와 같이 Contacts 컬렉션 속성의 Contact 항목은 컨트롤 태그 내에 지속됩니다.

<aspSample:QuickContacts ID="QuickContacts1" Runat="server">
  <aspSample:Contact Name="someone" Email="someone@example.com"     Phone="(555) 555-5555"/><aspSample:Contact Name="jae" Email="jae@fourthcoffee.com"     Phone="(555) 555-5555"/>
</aspSample:QuickContacts>

알기 쉽도록 하기 위해 QuickContacts 컨트롤은 컬렉션 속성에 대한 상태 관리를 구현하지 않습니다. 컬렉션 항목은 페이지에서 선언적으로 추가하는 것으로 가정되거나 코드를 통해 만들어진 경우에는 다시 게시할 때 다시 만들어야 합니다. 프로덕션 수준의 컨트롤에서는 상태 관리를 구현할 수 있습니다. 자세한 내용은 서버 컨트롤 사용자 지정 상태 관리를 참조하십시오.

QuickContacts 컨트롤에 대한 코드 목록

' QuickContacts.vb
Option Strict On
Imports System
Imports System.ComponentModel
Imports System.Collections
Imports System.Drawing.Design
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.VB.Controls
    < _
    AspNetHostingPermission(SecurityAction.Demand, _
        Level:=AspNetHostingPermissionLevel.Minimal), _
    AspNetHostingPermission(SecurityAction.InheritanceDemand, _
        Level:=AspNetHostingPermissionLevel.Minimal), _
    DefaultProperty("Contacts"), _
    ParseChildren(True, "Contacts"), _
    ToolboxData( _
        "<{0}:QuickContacts runat=""server""> </{0}:QuickContacts>") _
    > _
    Public Class QuickContacts
        Inherits WebControl

        Private contactsList As ArrayList

        < _
        Category("Behavior"), _
        Description("The contacts collection"), _
        DesignerSerializationVisibility( _
            DesignerSerializationVisibility.Content), _
        Editor(GetType(ContactCollectionEditor), _
            GetType(UITypeEditor)), _
        PersistenceMode(PersistenceMode.InnerDefaultProperty) _
        > _
        Public ReadOnly Property Contacts() As ArrayList
            Get
                If contactsList Is Nothing Then
                    contactsList = New ArrayList
                End If
                Return contactsList
            End Get
        End Property

        ' The contacts are rendered in an HTML table.
        Protected Overrides Sub RenderContents( _
        ByVal writer As HtmlTextWriter)
            Dim t As Table = CreateContactsTable()
            If t IsNot Nothing Then
                t.RenderControl(writer)
            End If
        End Sub

        Private Function CreateContactsTable() As Table
            Dim t As Table = Nothing
            If (contactsList IsNot Nothing) AndAlso _
                (contactsList.Count > 0) Then
                t = New Table
                For Each item As Contact In contactsList
                    Dim aContact As Contact = TryCast(item, Contact)
                    If aContact IsNot Nothing Then
                        Dim r As New TableRow
                        Dim c1 As New TableCell
                        c1.Text = aContact.Name
                        r.Controls.Add(c1)

                        Dim c2 As New TableCell
                        c2.Text = aContact.Email
                        r.Controls.Add(c2)

                        Dim c3 As New TableCell
                        c2.Text = aContact.Phone
                        r.Controls.Add(c3)

                        t.Controls.Add(r)
                    End If
                Next
            End If
            Return t
        End Function
    End Class
End Namespace
// QuickContacts.cs
using System;
using System.ComponentModel;
using System.Collections;
using System.Drawing.Design;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Samples.AspNet.CS.Controls
{
    [
    AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand, 
        Level=AspNetHostingPermissionLevel.Minimal),
    DefaultProperty("Contacts"),
    ParseChildren(true, "Contacts"),
    ToolboxData(
        "<{0}:QuickContacts runat=\"server\"> </{0}:QuickContacts>")
    ]
    public class QuickContacts : WebControl
    {
        private ArrayList contactsList;

        [
        Category("Behavior"),
        Description("The contacts collection"),
        DesignerSerializationVisibility(
            DesignerSerializationVisibility.Content),
        Editor(typeof(ContactCollectionEditor), typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerDefaultProperty)
        ]
        public ArrayList Contacts
        {
            get
            {
                if (contactsList == null)
                {
                    contactsList = new ArrayList();
                }
                return contactsList;
            }
        }


        // The contacts are rendered in an HTML table.
        protected override void RenderContents(
            HtmlTextWriter writer)
        {
            Table t = CreateContactsTable();
            if (t != null)
            {
                t.RenderControl(writer);
            }
        }

        private Table CreateContactsTable()
        {
            Table t = null;

            if (contactsList != null && contactsList.Count > 0)
            {
                t = new Table();

                foreach (Contact item in contactsList)
                {
                    Contact aContact = item as Contact;

                    if (aContact != null)
                    {
                        TableRow r = new TableRow();

                        TableCell c1 = new TableCell();
                        c1.Text = aContact.Name;
                        r.Controls.Add(c1);

                        TableCell c2 = new TableCell();
                        c2.Text = aContact.Email;
                        r.Controls.Add(c2);


                        TableCell c3 = new TableCell();
                        c3.Text = aContact.Phone;
                        r.Controls.Add(c3);

                        t.Controls.Add(r);
                    }
                }
            }
            return t;
        }
    }
}

코드 설명

컨트롤 태그 내에서 컬렉션 항목을 구문 분석할 수 있도록 QuickContacts 컨트롤은 ParseChildren(true, "Contacts") 특성을 컨트롤에 추가합니다. ParseChildrenAttribute의 첫 번째 인수(true)는 페이지 파서가 컨트롤 태그에 포함된 중첩 내용을 자식 컨트롤이 아니라 속성으로 해석해야 함을 지정합니다. 두 번째 인수("Contacts")는 내부 기본 속성의 이름을 제공합니다. 두 번째 인수를 지정하는 경우 컨트롤 태그에 포함된 내용이 기본 내부 속성(Contact 개체)과만 일치해야 합니다.

또한 QuickContacts 컨트롤에는 디자인 타임 serialization 및 지속성을 위해 컬렉션 속성에 적용해야 할 다음과 같은 디자인 타임 특성도 포함되어 있습니다.

  • DesignerSerializationVisibilityAttribute   Content 매개 변수를 설정하면 비주얼 디자이너에서 속성의 내용을 serialize해야 합니다. 이 예제의 경우에는 속성에 Contact 개체가 포함되어 있습니다.

  • PersistenceModeAttribute   InnerDefaultProperty 매개 변수를 전달하면 비주얼 디자이너에서는 특성이 내부 기본 속성으로 적용되는 속성을 지속해야 합니다. 즉, 컨트롤 태그 내에서 속성이 지속됩니다. 컨트롤 태그 내에 지속될 수 있는 속성은 하나뿐이므로 하나의 속성에만 특성을 적용할 수 있습니다. 속성 값은 특수 태그에서 래핑되지 않습니다.

다음 예제와 같이 QuickContacts 컨트롤은 EditorAttribute를 사용하여 컬렉션 편집기를 Contacts 컬렉션 속성과 연결합니다.

Editor(typeof(ContactCollectionEditor), typeof(UITypeEditor))
Editor(GetType(ContactCollectionEditor), GetType(UITypeEditor))

컬렉션 편집기를 속성과 연결하면 Contact 항목을 추가할 수 있는 컬렉션 편집기를 비주얼 디자이너의 속성 브라우저에서 열 수 있습니다. 이것은 DropDownList 또는 ListBox 컨트롤의 Items 속성을 편집할 수 있는 UI(사용자 인터페이스)와 비슷합니다. QuickContacts에서 사용하는 사용자 지정 컬렉션 편집기인 ContactCollectionEditor에 대한 내용은 컬렉션 편집기 예제에서 설명합니다.

알기 쉽도록 하기 위해 QuickContacts 컨트롤은 강력한 형식의 컬렉션을 정의하지 않고 대신 컬렉션 형식에 대해 ArrayList를 사용합니다. 일반적으로는 응용 프로그램 개발자가 컬렉션에 임의의 형식을 추가할 수 없도록 강력한 형식의 컬렉션을 컬렉션 속성 형식으로 사용해야 합니다.

Contact 클래스에 대한 코드 목록

Contact 클래스 코드의 디자인 타임 특성은 속성 편집 및 디자인 타임 serialization을 수행하는 데 필요합니다. TypeConverterAttribute를 사용하여 Contact 클래스와 연결된 ExpandableObjectConverter 형식 변환기를 사용하면 컬렉션 편집기에서 하위 속성(Name, Email, Phone)을 편집할 때 확장/축소 사용자 인터페이스를 사용할 수 있습니다. 이것은 비주얼 디자이너의 속성 브라우저에서 웹 컨트롤의 Font 속성을 편집할 때 표시되는 UI와 비슷합니다. 생성자 인수가 true인 NotifyParentPropertyAttribute가 Name, Email 및 Phone 속성에 적용되면 편집기에서는 이러한 속성의 변경 내용을 부모 속성, 즉 Contact 클래스의 인스턴스로 serialize합니다.

' Contact.vb
' The type of the items in the Contacts collection property 
' in QuickContacts.
Option Strict On
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Web.UI

Namespace Samples.AspNet.VB.Controls
    < _
    TypeConverter(GetType(ExpandableObjectConverter)) _
    > _
    Public Class Contact
        Private _name As String
        Private _email As String
        Private _phone As String

        Public Sub New()
            Me.New(String.Empty, String.Empty, String.Empty)
        End Sub

        Public Sub New(ByVal name As String, _
        ByVal email As String, ByVal phone As String)
            _name = name
            _email = email
            _phone = phone
        End Sub

        < _
        Category("Behavior"), _
        DefaultValue(""), _
        Description("Name of contact"), _
        NotifyParentProperty(True) _
        > _
        Public Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        < _
        Category("Behavior"), _
        DefaultValue(""), _
        Description("Email address of contact"), _
        NotifyParentProperty(True) _
        > _
        Public Property Email() As String
            Get
                Return _email
            End Get
            Set(ByVal value As String)
                _email = value
            End Set
        End Property


        < _
        Category("Behavior"), _
        DefaultValue(""), _
        Description("Phone number of contact"), _
        NotifyParentProperty(True) _
        > _
        Public Property Phone() As String
            Get
                Return _phone
            End Get
            Set(ByVal value As String)
                _phone = value
            End Set
        End Property
    End Class
End Namespace
// Contact.cs
// The type of the items in the Contacts collection property 
//in QuickContacts.

using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;

namespace Samples.AspNet.CS.Controls
{
    [
    TypeConverter(typeof(ExpandableObjectConverter))
    ]
    public class Contact
    {
        private string nameValue;
        private string emailValue;
        private string phoneValue;


        public Contact()
            : this(String.Empty, String.Empty, String.Empty)
        {
        }

        public Contact(string name, string email, string phone)
        {
            nameValue = name;
            emailValue = email;
            phoneValue = phone;
        }

        [
        Category("Behavior"),
        DefaultValue(""),
        Description("Name of contact"),
        NotifyParentProperty(true),
        ]
        public String Name
        {
            get
            {
                return nameValue;
            }
            set
            {
                nameValue = value;
            }
        }

        [
        Category("Behavior"),
        DefaultValue(""),
        Description("Email address of contact"),
        NotifyParentProperty(true)
        ]
        public String Email
        {
            get
            {
                return emailValue;
            }
            set
            {
                emailValue = value;
            }
        }

        [
        Category("Behavior"),
        DefaultValue(""),
        Description("Phone number of contact"),
        NotifyParentProperty(true)
        ]
        public String Phone
        {
            get
            {
                return phoneValue;
            }
            set
            {
                phoneValue = value;
            }
        }
    }
}

QuickContacts 컨트롤에 대한 테스트 페이지

다음 예제에서는 QuickContacts 컨트롤을 사용하는 .aspx 페이지를 보여 줍니다.

<%@ Page Language="VB"%>
<!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 id="Head1" >
    <title>
      QuickContacts test page
    </title>
  </head>
  <body>
    <form id="Form1" >
      <aspSample:QuickContacts ID="QuickContacts1" Runat="server" 
        BorderStyle="Solid" BorderWidth="1px">
        <aspSample:Contact Name="someone" Email="someone@example.com" 
          Phone="(555) 555-0100"/>
        <aspSample:Contact Name="jae" Email="jae@fourthcoffee.com" 
          Phone="(555) 555-0101"/>
        <aspSample:Contact Name="lene" Email="lene@contoso.com" 
          Phone="(555) 555-0102"/>        
      </aspSample:QuickContacts>
    </form>
  </body>
</html>
<%@ Page Language="C#"%>
<!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 id="Head1" >
    <title>
      QuickContacts test page
    </title>
  </head>
  <body>
    <form id="Form1" >
      <aspSample:QuickContacts ID="QuickContacts1" Runat="server" 
        BorderStyle="Solid" BorderWidth="1px">
        <aspSample:Contact Name="someone" Email="someone@example.com" 
          Phone="(555) 555-0100"/>
        <aspSample:Contact Name="jae" Email="jae@fourthcoffee.com" 
          Phone="(555) 555-0101"/>
        <aspSample:Contact Name="lene" Email="lene@contoso.com" 
          Phone="(555) 555-0102"/>        
      </aspSample:QuickContacts>
    </form>
  </body>
</html>

예제 빌드 및 사용

컬렉션 편집기 예제에 나열된 ContactCollectionEditor 편집기를 사용하여 QuickContacts 컨트롤과 Contacts 클래스를 컴파일합니다. 컴파일에 사용할 System.Design 어셈블리에 대한 참조를 추가해야 합니다.

사용자 지정 컨트롤 예제의 컴파일 및 사용에 대한 자세한 내용은 사용자 지정 서버 컨트롤 예제 빌드를 참조하십시오.

참고 항목

개념

컬렉션 편집기 예제

사용자 지정 서버 컨트롤 예제 빌드

기타 리소스

사용자 지정 ASP.NET 서버 컨트롤 개발