ASP.NET Tutorial/Custom Controls/Introduction — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:00, 26 мая 2010

Differences between user controls and web pages

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">
    <div>
        <h2>A Page With a Configurable Footer</h2>
    <br /><br /><br />
    <hr />
    
    <asp:RadioButton id="optShort" runat="server" GroupName="Format" Text="Short Format"></asp:RadioButton>
    <br />
    <asp:RadioButton id="optLong" runat="server" GroupName="Format" Text="Long Format"></asp:RadioButton>
    <br /><br />
    <asp:Button id="cmdRefresh" runat="server" Text="Refresh"></asp:Button>
    <hr />
    <br />
    <nfex:Footer id="Footer1" runat="server"></nfex:Footer>
    </div>
    </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;
        }
    }
}


Exposing Properties from a User Control

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" />
<br />
<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">
    <div>
    <user:PropertyRandomImage
        ID="PropertyRandomImage1"
        ImageFolderPath="~/Images2"
        Runat="server" />
    </div>
    </form>
</body>
</html>


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

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: " & _
         "<br>id: " & LoginForm1.id & "<br>" & _
         "BackColor: " & LoginForm1.BackColor & "<br>" & _
         "Username: " & LoginForm1.Username & "<br>" & _
         "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: <b>" & User.Text & _
         "</b><br>" & "Password: <b>" & Pass.Text & "</b>"
   end sub
</script>
<table style="background-color:white;font: 10pt verdana;border-width:1;border-style:solid;border-color:black;" 
   cellspacing=15>
   <tr>
      <td><b>Login: </b></td>
      <td><ASP:TextBox id="User" runat="server"/></td>
   </tr>
   <tr>
      <td><b>Password: </b></td>
      <td><ASP:TextBox id="Pass" TextMode="Password" 
             runat="server"/></td>
   </tr>
   <tr>
      <td></td>
      <td><ASP:Button Text="Submit" runat="server" 
             OnClick="Submit" /></td>
   </tr>
</table>
<ASP:Label id="lblMessage" runat="server"/>


Page component with code behind (VB.net)

<%@ 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"/><br>
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


Page control with full qualified name(C#)

<%@ 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"/>


Set the properties from user control programmatically.

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" />
<br />
<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">
    <div>
    <user:PropertyRandomImage
        ID="PropertyRandomImage1"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Use properties defined in custom control

<%@ 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("<font size=" + this.Size + ">" + this.Message + "</font>");
      }
   }
}
////////////////
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("<font size=" & Me.Size & ">" & Me.Message & "</font>")
      End Sub
   End Class
End Namespace