다음을 통해 공유


웹 컨트롤 렌더링 예제

업데이트: 2007년 11월

이 예제에서는 mailto: URI가 포함된 하이퍼링크(<a>) 요소를 렌더링하여 웹 페이지에 전자 메일 링크를 만드는 MailLink라는컨트롤을 만드는 방법을 보여 줍니다. 이 컨트롤은 WebControl 클래스에서 파생되는 컨트롤을 렌더링할 때 일반적으로 수행할 작업을 보여 줍니다.

MailLink 컨트롤은 전자 메일 주소에 대한 Email 속성과 하이퍼링크에 표시할 텍스트에 대한 Text 속성을 노출합니다. 페이지 개발자는 아래 강조 표시된 텍스트와 같이 이러한 속성을 설정할 수 있습니다.

<aspSample:MailLink id="maillink1" Email="someone@example.com" 
    >
  Mail Webmaster
</aspSample:MailLink> 

컨트롤에서 렌더링한 태그가 클라이언트에 표시되면 다음과 같이 나타납니다.

<a id="maillink1" href="mailto:someone@example.com">
  Mail Webmaster
</a>

mailto: URI의 동작은 브라우저에 따라 다를 수 있습니다. Internet Explorer에서는 사용자가 mailto: 하이퍼링크를 클릭하면 사용자의 기본 전자 메일 클라이언트가 시작됩니다(전자 메일 클라이언트가 설치되어 있고 브라우저와 호환되는 경우). MailLink 컨트롤의 코드에 대해서는 이 항목의 뒷부분에 나오는 "코드 설명" 단원을 참조하십시오.

' MailLink.vb
Option Strict On
Imports System
Imports System.ComponentModel
Imports System.Security
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("Email"), _
    ParseChildren(True, "Text"), _
    ToolboxData("<{0}:MailLink runat=""server""> </{0}:MailLink>") _
    > _
    Public Class MailLink
        Inherits WebControl
        < _
        Bindable(True), _
        Category("Appearance"), _
        DefaultValue(""), _
        Description("The e-mail address.") _
        > _
        Public Overridable Property Email() As String
            Get
                Dim s As String = CStr(ViewState("Email"))
                If s Is Nothing Then s = String.Empty
                Return s
            End Get
            Set(ByVal value As String)
                ViewState("Email") = value
            End Set
        End Property

        < _
        Bindable(True), _
        Category("Appearance"), _
        DefaultValue(""), _
        Description("The text to display on the link."), _
        Localizable(True), _
        PersistenceMode(PersistenceMode.InnerDefaultProperty) _
        > _
        Public Overridable Property Text() As String
            Get
                Dim s As String = CStr(ViewState("Text"))
                If s Is Nothing Then s = String.Empty
                Return s
            End Get
            Set(ByVal value As String)
                ViewState("Text") = value
            End Set
        End Property

        Protected Overrides ReadOnly Property TagKey() _
            As HtmlTextWriterTag
            Get
                Return HtmlTextWriterTag.A
            End Get
        End Property


        Protected Overrides Sub AddAttributesToRender( _
            ByVal writer As HtmlTextWriter)
            MyBase.AddAttributesToRender(writer)
            writer.AddAttribute(HtmlTextWriterAttribute.Href, _
                "mailto:" & Email)
        End Sub

        Protected Overrides Sub RenderContents( _
            ByVal writer As HtmlTextWriter)
            If (Text = String.Empty) Then
                Text = Email
            End If
            writer.WriteEncodedText(Text)
        End Sub

    End Class
End Namespace
// MailLink.cs
using System;
using System.ComponentModel;
using System.Security;
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("Email"),
    ParseChildren(true, "Text"),
    ToolboxData("<{0}:MailLink runat=\"server\"> </{0}:MailLink>")
    ]
    public class MailLink : WebControl
    {
        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description("The e-mail address.")
        ]
        public virtual string Email
        {
            get
            {
                string s = (string)ViewState["Email"];
                return (s == null) ? String.Empty : s;
            }
            set
            {
                ViewState["Email"] = value;
            }
        }

        [
        Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description("The text to display on the link."),
        Localizable(true),
        PersistenceMode(PersistenceMode.InnerDefaultProperty)
        ]
        public virtual string Text
        {
            get
            {
                string s = (string)ViewState["Text"];
                return (s == null) ? String.Empty : s;
            }
            set
            {
                ViewState["Text"] = value;
            }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.A;
            }
        }

        protected override void AddAttributesToRender(
            HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            writer.AddAttribute(HtmlTextWriterAttribute.Href, 
                "mailto:" + Email);
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (Text == String.Empty)
            {
                Text = Email;
            }
            writer.WriteEncodedText(Text);
        }
    }
}

코드 설명

MailLink 컨트롤 예제에서는 다음과 같은 작업을 보여 줍니다.

  • 컨트롤의 기본 요소가 아닌 요소 렌더링

  • 컨트롤의 여는 태그에서 특성 렌더링

  • 컨트롤 태그 내에 내용 렌더링

MailLink 컨트롤은 WebControl 클래스에서 렌더링하는 기본 <span> 요소 대신 <a> 요소를 렌더링하도록 TagKey 속성을 재정의합니다. 렌더링할 요소가 HtmlTextWriterTag 열거형의 멤버인 경우 TagKey 속성을 재정의해야 합니다. 대부분의 일반 HTML 요소 태그는 HtmlTextWriterTag 열거형의 값에 매핑됩니다. 예를 들어 HtmlTextWriterTag.A는 <a> 요소에 대응하고 HtmlTextWriterTag.Table은 <table> 요소에 대응합니다. 렌더링할 요소가 HtmlTextWriterTag 열거형의 멤버로 표시되지 않는 경우에는 TagName 속성을 재정의하고 요소로 렌더링할 문자열을 반환합니다.

MailLink 컨트롤은 다음과 같이 WebControl 클래스의 렌더링 메서드를 재정의합니다.

  • AddAttributesToRender를 재정의하여 컨트롤에서 렌더링하는 href 특성을 여는 태그에 추가할 수 있습니다. MailLink 컨트롤에서 보여 주는 것처럼 AddAttributesToRender를 재정의할 경우에는 항상 기본 클래스의 해당 메서드를 호출해야 합니다. WebControl 클래스의 AddAttributesToRender 메서드는 웹 컨트롤에서 렌더링하는 스타일 및 다른 특성을 요소에 추가하는 논리를 구현하고 WebControlRenderBeginTag 메서드에서 호출됩니다. 여는 태그를 렌더링하기 전에 특성을 추가해야 합니다. 즉, AddAttributesToRender 또는 AddAttribute에 대한 호출이 RenderBeginTag에 대한 호출보다 앞에 옵니다.

  • RenderContents를 재정의하여 컨트롤 태그 내에 하이퍼링크에 대한 텍스트를 작성할 수 있습니다(Text 속성에 지정). MailLink 컨트롤은 HtmlTextWriter 인스턴스의 WriteEncodedText 메서드를 호출하여 페이지 개발자가 입력한 텍스트를 HTML로 인코딩합니다. 보안을 위해 일반적으로 사용자가 입력한 텍스트를 HTML로 인코딩해야 합니다.

MailLink 컨트롤에서는 내부 텍스트 지속성도 보여 줍니다. 페이지 개발자는 MailLink를 사용하여 아래 강조 표시된 텍스트와 같이 컨트롤 태그 내에 Text 속성을 지정할 수 있습니다.

<aspSample:MailLink id="maillink1" Email="someone@example.com" 
    >
  Mail Webmaster
</aspSample:MailLink>

다음 예제에서 알 수 있듯이 내부 지속성은 컨트롤의 여는 태그에서 기본 지속성과 대조를 이룹니다.

<aspSample:MailLink Text="Mail Webmaster"  />

기본 지속성과 내부 지속성은 기능적으로 동일합니다. 내부 지속성을 사용하기 위해 MailLink가 ParseChildren(true, "Text") 특성으로 표시되어 있습니다. ParseChildrenAttribute 생성자의 첫 번째 인수는 페이지 파서가 컨트롤 태그에 포함된 내용을 자식 컨트롤이 아니라 속성으로 구문 분석해야 함을 지정합니다. 두 번째 인수는 컨트롤에 대한 내부 기본 속성의 이름(이 예제의 경우 Text)을 제공합니다. 이러한 두 매개 변수를 사용하여 ParseChildrenAttribute 생성자를 호출하는 경우 컨트롤 태그에 포함된 내용이 내부 기본 속성과 일치해야 합니다. Text 속성의 PersistenceMode(PersistenceMode.InnerDefaultProperty) 특성은 비주얼 디자이너에서 이 속성을 컨트롤 태그에 포함된 내부 내용으로 serialize해야 함을 지정합니다.

WebControl은 디자인 타임 및 구문 분석 타임 속성 지속성을 결정하는 PersistChildren(false) 특성과 ParseChildren(true) 특성으로 표시되어 있습니다. 이러한 두 특성은 컨트롤과 함께 상속되며 상속된 설정을 변경할 경우에만 적용해야 합니다. PersistChildrenAttribute는 서버 컨트롤의 자식 컨트롤이 중첩 내부 컨트롤로 지속되는지 여부를 디자이너에 알려 줍니다. false 인수는 내부 내용이 자식 컨트롤과 일치하지 않고 속성과 일치함을 나타냅니다. ParseChildrenAttribute에 대해서는 이전 단락에서 설명했습니다. WebControl 클래스의 디자인 타임 및 구문 분석 타임 지속성이 컨트롤에 적합한 경우에는 WebControl에서 상속된 PersistChildrenAttributeParseChildrenAttribute 특성을 재정의할 필요가 없습니다.

다음 예제에서는 MailLink 컨트롤을 사용하는 ASP.NET 웹 페이지(.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>MailLink test page</title>
</head>
<body>
  <form id="Form1" >
    <aspSample:MailLink id="maillink1" Font-Bold="true" 
      ForeColor="Green" Email="someone@example.com" >
      Mail Webmaster
    </aspSample:MailLink>
  </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>MailLink test page</title>
</head>
<body>
  <form id="Form1" >
    <aspSample:MailLink id="maillink1" Font-Bold="true" 
      ForeColor="Green" Email="someone@example.com" >
      Mail Webmaster
    </aspSample:MailLink>
  </form>
</body>
</html>

예제 빌드 및 사용

컨트롤을 빌드하고 페이지에서 사용하는 데 대한 내용은 사용자 지정 서버 컨트롤 예제 빌드를 참조하십시오.

참고 항목

기타 리소스

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