ASP.NET Tutorial/Custom Controls/Introduction

Материал из .Net Framework эксперт
Версия от 15:00, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Differences between user controls and web pages

   <source lang="csharp">

User controls use the file extension .ascx instead of .aspx User controls" code-behind files inherit from the System.Web.UI.UserControl class. The .ascx file for a user control begins with a <%@ Control %> directive instead of a <%@ Page %> directive. User controls can"t be requested directly by a web browser. Instead, they must be embedded inside other web pages.

File: Control.ascx <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Control.ascx.cs" Inherits="Footer" %> <asp:Label id="lblFooter" runat="server" /> File: Control.ascx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Footer : System.Web.UI.UserControl {

   protected void Page_Load(object sender, EventArgs e)
   {
       lblFooter.Text = "This page was served at ";
       if (format == FooterFormat.LongDate)
       {
           lblFooter.Text += DateTime.Now.ToLongDateString();
       }
       else if (format == FooterFormat.ShortTime)
       {
           lblFooter.Text += DateTime.Now.ToShortTimeString();
       }
   }
   public enum FooterFormat
   { LongDate, ShortTime }
   private FooterFormat format = FooterFormat.LongDate;
   public FooterFormat Format
   {
       get { return format; }
       set { format = value; }
   }

} File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="FooterHost" %> <%@ Register TagPrefix="nfex" TagName="Footer" Src="Control.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Footer Host</title>

</head> <body>

   <form id="form1" runat="server">

A Page With a Configurable Footer

   



   <asp:RadioButton id="optShort" runat="server" GroupName="Format" Text="Short Format"></asp:RadioButton>
   
<asp:RadioButton id="optLong" runat="server" GroupName="Format" Text="Long Format"></asp:RadioButton>

<asp:Button id="cmdRefresh" runat="server" Text="Refresh"></asp:Button>

   
<nfex:Footer id="Footer1" runat="server"></nfex:Footer>
   </form>

</body> </html> File: Default.aspx.cs

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class FooterHost : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
       if (optLong.Checked)
       {
           Footer1.Format = Footer.FooterFormat.LongDate;
       }
       else if (optShort.Checked)
       {
           Footer1.Format = Footer.FooterFormat.ShortTime;
       }
   }

}</source>


Exposing Properties from a User Control

   <source lang="csharp">

File: Control.ascx <%@ Control Language="C#" ClassName="PropertyRandomImage" %> <%@ Import Namespace="System.IO" %> <script runat="server">

   private string _imageFolderPath = "~/Images";
   public string ImageFolderPath
   {
       get { return _imageFolderPath; }
       set { _imageFolderPath = value; }
   }
   void Page_Load()
   {
       string imageToDisplay = GetRandomImage();
       imgRandom.ImageUrl = Path.rubine(_imageFolderPath, imageToDisplay);
       lblRandom.Text = imageToDisplay;
   }
   private string GetRandomImage()
   {
       Random rnd = new Random();
       string[] images = Directory.GetFiles(MapPath("~/Images"), "*.jpg");
       string imageToDisplay = images[rnd.Next(images.Length)];
       return Path.GetFileName(imageToDisplay);
   }

</script> <asp:Image

   id="imgRandom"
   Width="300px"
   Runat="server" />


<asp:Label

   id="lblRandom"
   Runat="server" />

File: ShowDeclarative.aspx <%@ Page Language="C#" %> <%@ Register TagPrefix="user" TagName="PropertyRandomImage" Src="~/Control.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Show Declarative</title>

</head> <body>

   <form id="form1" runat="server">
   <user:PropertyRandomImage
       ID="PropertyRandomImage1"
       ImageFolderPath="~/Images2"
       Runat="server" />
   </form>

</body> </html></source>


Get value from asp.net page control (VB.net)

   <source lang="csharp">

File: index.aspx <%@ Page Language="VB" %> <%@ Register TagPrefix="nfexASP" TagName="LoginForm" src="Control.ascx" %> <script runat="server">

  sub Page_Load(Sender as Object, e as EventArgs)
     lblMessage.Text = "Properties of the user control: " & _
        "
id: " & LoginForm1.id & "
" & _ "BackColor: " & LoginForm1.BackColor & "
" & _ "Username: " & LoginForm1.Username & "
" & _ "Password: " & LoginForm1.Password end sub

</script> <html><body>

  <form runat="server">
     <nfexASP:LoginForm id="LoginForm1" runat="server" 
        Password="MyPassword"
        Username="Chris"
        BackColor="Beige" />
  </form>
  
  <asp:Label id="lblMessage" runat="server" />

</body></html> File: Control.ascx <script language="VB" runat="server">

  public BackColor as String = "White"
  public property UserName as string
     Get
        UserName = User.Text
     End Get
     Set
        User.Text = value
     End Set
  end property
  public property Password as string
     Get
        Password = Pass.Text
     End Get
     Set
        Pass.Text = value
     End Set
  end property
  
  public sub Submit(obj as object, e as eventargs)
     lblMessage.Text = "Username: " & User.Text & _
        "
" & "Password: " & Pass.Text & "" end sub

</script>

Login: <ASP:TextBox id="User" runat="server"/>
Password: <ASP:TextBox id="Pass" TextMode="Password" runat="server"/>
<ASP:Button Text="Submit" runat="server" OnClick="Submit" />

<ASP:Label id="lblMessage" runat="server"/></source>


Page component with code behind (VB.net)

   <source lang="csharp">

<%@ Page language="VB" %> <%@ Register TagPrefix="nfex" TagName="Calculator" src="Control.ascx" %> <html><body>

  <form runat="server">
     <nfex:Calculator id="Calc1" runat="server"/>
  </form>

</body></html> File: Control.ascx <%@ Control Inherits="CalculatorControl" src="Control.ascx.vb" %> Number 1: <asp:textbox id="tbNumber1" runat="server"/>
Number 2: <asp:textbox id="tbNumber2" runat="server"/> <asp:button id="btAdd" runat="server" Text="+"

  OnClick="btOperator_Click" />

<asp:button id="btSubtract" runat="server" Text="-"

  OnClick="btOperator_Click"/>

<asp:button id="btMultiply" runat="server" Text="*"

  OnClick="btOperator_Click"/>

<asp:button id="btDivide" runat="server" Text="/"

  OnClick="btOperator_Click"/>

The answer is: <asp:label id="lblMessage" runat="server"/> File: Control.ascx.vb

Imports System Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Public Class CalculatorControl : Inherits UserControl

  public lblMessage as Label
  public btAdd as Button
  public btSubtract as Button
  public btMultiply as Button
  public btDivide as Button
  public tbNumber1 as TextBox
  public tbNumber2 as TextBox
  
  Sub btOperator_Click(Sender as Object, e as EventArgs)
     lblMessage.Text = Operate(CType(Sender, Button).Text, _
        tbNumber1.Text, tbNumber2.Text).ToString
  End Sub
  
  private function Operate(op as string, number1 as string, number2 as string) as double
     select case op
        case "+"
           Operate = CInt(number1) + CInt(number2)
        case "-"
           Operate = CInt(number1) - CInt(number2)
        case "*"
           Operate = CInt(number1) * CInt(number2)
        case "/"
           Operate = CInt(number1) / CInt(number2)
     end select
  end function

End Class</source>


Page control with full qualified name(C#)

   <source lang="csharp">

<%@ Page Language="C#" %> <%@ Register TagPrefix="MyControl" TagName="View" Src="Control.ascx" %> <script runat="server">

  void Page_Load(Object Sender, EventArgs e) {
     lblMessage.Text = "Page last viewed at " + DateTime.Now.ToString("T");
  }

</script> <html><body>

  <MyControl:View runat="server" />   
  <asp:Label id="lblMessage" runat="server"/>

</body></html> File: Control.ascx

<%@ Control Language="VB" %> <%@ OutputCache Duration="30" VaryByParam="none" %> <script runat="server">

  sub Page_Load(Sender as Object, e as EventArgs)
     lblMessage.Text = "Control last viewed at " & _
        DateTime.Now.ToString("T")
  end sub   

</script> <asp:Label id="lblMessage" runat="server"/></source>


Set the properties from user control programmatically.

   <source lang="csharp">

File: Control.ascx <%@ Control Language="C#" ClassName="PropertyRandomImage" %> <%@ Import Namespace="System.IO" %> <script runat="server">

   private string _imageFolderPath = "~/Images";
   public string ImageFolderPath
   {
       get { return _imageFolderPath; }
       set { _imageFolderPath = value; }
   }
   void Page_Load()
   {
       string imageToDisplay = GetRandomImage();
       imgRandom.ImageUrl = Path.rubine(_imageFolderPath, imageToDisplay);
       lblRandom.Text = imageToDisplay;
   }
   private string GetRandomImage()
   {
       Random rnd = new Random();
       string[] images = Directory.GetFiles(MapPath("~/Images"), "*.jpg");
       string imageToDisplay = images[rnd.Next(images.Length)];
       return Path.GetFileName(imageToDisplay);
   }

</script> <asp:Image

   id="imgRandom"
   Width="300px"
   Runat="server" />


<asp:Label

   id="lblRandom"
   Runat="server" />

File: Default.aspx <%@ Page Language="C#" %> <%@ Register TagPrefix="user" TagName="PropertyRandomImage" Src="~/Control.ascx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server">

   protected void Page_Load(object sender, EventArgs e)
   {
       PropertyRandomImage1.ImageFolderPath = "~/Images2";
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Show Programmatic</title>

</head> <body>

   <form id="form1" runat="server">
   <user:PropertyRandomImage
       ID="PropertyRandomImage1"
       Runat="server" />
   </form>

</body> </html></source>


Use properties defined in custom control

   <source lang="csharp">

<%@ Page Language="VB" %> <%@ Register TagPrefix="nfexASP" Namespace="MyCustomControls" Assembly="CustomControls"%> <script runat="server">

  sub Submit(Sender as Object, e as EventArgs)
     MyControl.Size = MyControl.Size + 1
  end sub

</script> <html><body>

  <form runat=server>
     The custom control produces the following output:
  
     <nfexASP:CustomControl2 id="MyControl" runat=server 
        Message="Hello world!"
        Size=1 />
        
     <asp:Button runat="server"
        Text="Increase size!" 
        OnClick="Submit"/>
  </form>

</body></html> //////// using System; using System.Web; using System.Web.UI; namespace MyCustomControls {

  public class CustomControl2 : Control {
     public string Message {
        get {
           return ViewState["Message"].ToString();
        }
        set {
           ViewState["Message"] = value;
        }
     }
     
     public int Size {
        get {
           return (int)ViewState["Size"];
        }
        set {
           ViewState["Size"] = value;
        }
     }
     protected override void Render(HtmlTextWriter Output) {
        Output.Write("" + this.Message + "");
     }
  }

} //////////////// Imports System Imports System.Web Imports System.Web.UI Namespace MyCustomControls

  Public Class CustomControl2 : Inherits Control
     public property Message as string
        Get
           Message = ViewState("Message").ToString
        End Get
        Set
           ViewState("Message") = value
        End Set
     end property
     
     public property Size as integer
        Get
           Size = CType(ViewState("Size"), Integer)
        End Get
        Set
           ViewState("Size") = value
        End Set
     end property
     Protected Overrides Sub Render(Output as HtmlTextWriter)
        Output.Write("" & Me.Message & "")
     End Sub
  End Class

End Namespace</source>