缤纷多彩的植物信息世界

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

1、目录

2、一些另外的标准ASP.NET服务器控件概述

2.1 控件列表

2.2 对象模型

Control类除了有一个visibility属性外,没有其他与用户界面相关的属性函数,它提供所有控件所需要的基本特征,例如:ID,子控件集合,共有的控件事件。对比来说,WebControl类主要提供一些控件的外表和行为的属性,比如前景色,高度和样式表等(ForeColor, Height, CssClass, etc.).

3、Panel Control

Panel控件经常用于创建一些控件组行为,比如定义页面中某个区域的外表,显示或隐藏页面中一群控件。

3.1 属性

Panel控件和HTML源码显示为<fieldset>和<legend>元素,<fieldset>用来定义一个表单中表单组,从而把一个表单分割成小的单元,在页面的显示效果是一个矩形框。<legend>元素定义小表单组的标题. 如下图所示

3.2 示例代码

PizzaPanelTest.aspx

<div id="left">
        <asp:Panel ID="panPizza" runat="server" Width="25em" GroupingText="Pizza Order Form">
            <dl>
                <dt>
                    <asp:Label ID="labCustomer" runat="server" Text="Customer" AccessKey="C" AssociatedControlID="txtCustomer" />
                </dt>
                <dd>
                    <asp:TextBox ID="txtCustomer" runat="server" />
                </dd>
                <dt>
                    <asp:Label ID="labPhone" runat="server" Text="Phone" AssociatedControlID="txtPhone" />
                </dt>
                <dd>
                    <asp:TextBox ID="txtPhone" runat="server" Columns="10" />
                </dd>
                <dt>
                    <asp:Label ID="labDelivery" runat="server" Text="Delivery" AssociatedControlID="chkDelivery" />
                </dt>
                <dd>
                    <asp:CheckBox ID="chkDelivery" runat="server" AutoPostBack="True" />
                </dd>
                <dt>
                    <asp:Label ID="labAddress" runat="server" Text="Address" AssociatedControlID="txtAddress" />
                </dt>
                <dd>
                    <asp:TextBox ID="txtAddress" runat="server" Columns="30" />
                </dd>
                <dt>
                    <asp:Label ID="labSize" runat="server" Text="Size" AssociatedControlID="drpSize" />
                </dt>
                <dd>
                    <asp:DropDownList ID="drpSize" runat="server" AutoPostBack="True">
                        <asp:ListItem Value="U">
Choose a size</asp:ListItem>
                        <asp:ListItem Value="S">Small</asp:ListItem>
                        <asp:ListItem Value="M">Medium</asp:ListItem>
                        <asp:ListItem Value="L">Large</asp:ListItem>
                    </asp:DropDownList>
                </dd>
                <dt>
                    <asp:Label ID="labToppings" runat="server" Text="Toppings" AssociatedControlID="clstToppings" />
                </dt>
                <dd>
                    <asp:CheckBoxList ID="clstToppings" runat="server" AutoPostBack="True">
                        <asp:ListItem Value="0">Ham</asp:ListItem>
                        <asp:ListItem Value="1">Pepperoni</asp:ListItem>
                        <asp:ListItem Value="2">
Extra Cheese</asp:ListItem>
                        <asp:ListItem Value="3">Mushrooms</asp:ListItem>
                        <asp:ListItem Value="4">
Green Peppers</asp:ListItem>
                    </asp:CheckBoxList>
                </dd>
                <dt>
                    <asp:Label ID="labCrust" runat="server" Text="Crust" AssociatedControlID="rlstCrust" />
                </dt>
                <dd>
                    <asp:RadioButtonList ID="rlstCrust" runat="server" AutoPostBack="True">
                        <asp:ListItem Selected="True">
Normal</asp:ListItem>
                        <asp:ListItem>Thin</asp:ListItem>
                        <asp:ListItem>Thick</asp:ListItem>
                    </asp:RadioButtonList>
                </dd>
            </dl>
        </asp:Panel>
    </div>
    <div id="right">
        <asp:Panel ID="panPricing" runat="server" Width="18em" GroupingText="Pricing">
            <asp:Literal ID="litPricing" runat="server" />
            <p>
                <asp:Button ID="btnOrder" runat="server" Text="Order Pizza" OnClick="btnOrder_Click" />
            </p>
        </asp:Panel>
        <asp:Panel ID="panOrder" runat="server" GroupingText="Final Order" Width="18em">
            <asp:Label ID="labOrder" runat="server" />
        </asp:Panel>
    </div>
PizzaPanelTest.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class PizzaPanelTest : System.Web.UI.Page
{
    // Data members used by the form
    // M indicates a decimal literal
    private decimal pizzaBase = 0.0M;
    private decimal pizzaToppings = 0.0M;
    /// <summary>
    /// Called each time page is requested or posted back
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Initialize the visibility of our controls and panels
        txtAddress.Visible = false;
        labAddress.Visible = false;
        panPricing.Visible = false;
        panOrder.Visible = false;
        if (IsPostBack)
        {
            // If delivery check box is checked, show address
            // NOTE: this is what you have to do if not using panels
            if (IsDelivery())
            {
                labAddress.Visible = true;
                txtAddress.Visible = true;
            }
            // If valid size has been selected, display pricing
            // panel and the pricing table within it
            if (IsValidSize())
            {
                panPricing.Visible = true;
                GeneratePricingTable();
            }
        }
    }
    /// <summary>
    /// Is this a delivery pizza?
    /// </summary>
    private bool IsDelivery()
    {
        if (this.chkDelivery.Checked)
            return true;
        else
            return false;
    }
    /// <summary>
    /// Calculate the price based on the size
    /// </summary>
    private void CalculatePrices()
    {
        // Calculate based on size
        if (this.drpSize.SelectedValue == "S")
            pizzaBase = 10.0M;
        else if (this.drpSize.SelectedValue == "M")
            pizzaBase = 15.0M;
        else if (this.drpSize.SelectedValue == "L")
            pizzaBase = 20.0M;
        // Now add $1.50 for each topping
        foreach (ListItem item in this.clstToppings.Items)
        {
            if (item.Selected)
                pizzaToppings += 1.50M;
        }
    }
    /// <summary>
    /// Was a valid pizza size selected
    /// 
    /// </summary>
    private bool IsValidSize()
    {
        if (this.drpSize.SelectedValue != "U")
            return true;
        else
            return false;
    }
    /// <summary>
    /// Generates the pricing table control
    /// </summary>
    private void GeneratePricingTable()
    {
        litPricing.Text = "<dl>";
        CalculatePrices();
        litPricing.Text +=
        CreatePricingRow("Base Price", pizzaBase, false);
        litPricing.Text +=
        CreatePricingRow("Toppings", pizzaToppings, false);
        decimal delivCharge = 0.0M;
        if (IsDelivery())
        {
            delivCharge = 1.00M;
            litPricing.Text +=
            CreatePricingRow("Delivery", delivCharge, false);
        }
        decimal subtotal = pizzaBase + pizzaToppings + delivCharge;
        decimal tax = subtotal * 0.07M;
        litPricing.Text += CreatePricingRow("Tax", tax, false);
        decimal total = subtotal + tax;
        litPricing.Text += CreatePricingRow("Total", total, true);
    }
    /// <summary>
    /// Create a row for the pricing table
    /// </summary>
    private string CreatePricingRow(string label, decimal value, bool isBold)
    {
        string s = "<dt id='item'>" + label + "</dt>";
        s += "<dd id='price'>";
        if (isBold) s += "<strong>";
        s += String.Format("{0:c}", value);
        if (isBold) s += "</strong>";
        s += "</dd>";
        return s;
    }
    /// <summary>
    /// Called when order button is clicked
    /// </summary>
    /// 
    protected void btnOrder_Click(object sender, EventArgs e)
    {
        // Construct order summary
        String s = "<b>" + drpSize.SelectedItem.Text +" Pizza Ordered</b><br/>";
        s += "For " + this.txtCustomer.Text + "<br>";
        if (IsDelivery())
        s += "Deliver to " + this.txtAddress.Text + "<br>";
        s += rlstCrust.SelectedItem.Text + " Crust<br>";
        s += "<b>Toppings:</b><br>";
        foreach (ListItem item in this.clstToppings.Items)
        {
            if (item.Selected)
                s += item.Text + "<br>";
        }
        // Display order summary panel and content
        panOrder.Visible = true;
        labOrder.Text = s;
    }
}

运行效果

4、MultiView and View Controls

4.1 属性和事件

4.2 视图间的导航Navigation Between Views

<asp:View ID="view2" runat="Server">
Content for view 2 here …
<asp:Button id="view2Prev" Text="Previous" runat="Server"
CommandName="PrevView">
</asp:Button>
<asp:Button id="view2Next" Text="Next" runat="Server"
CommandName="NextView">
</asp:Button>
<asp:Button id="view2Start" Text="Start Over" runat="Server"
CommandName="SwitchViewByIndex" CommandArgument="0">
</asp:Button>
</asp:View>

4.3 通过MultiView创建一个标签式的浏览视图

MultiViewTest.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiViewTestaspx.aspx.cs"
    Inherits="MultiViewTestaspx" %>
 
<!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></title>
    <style type="text/css">
        TabContainer
        {
            font: bold 0.75em Verdana;
            width: 60em;
            margin-top: 1.5em;
            padding-top: 2em;
        }
        .TabItemInactive
        {
            border-top: 1px solid white;
            border-left: 1px solid white;
            border-right: 1px solid #aaaaaa;
            border-bottom: none;
            background-color: #d3d3d3;
            text-align: center;
            text-decoration: none;
            padding: 0.75em 0.25em 0 0.25em;
        }
        .TabItemInactive:hover
        {
            background: #808080;
        }
        .TabItemActive
        {
            border-top: 1px solid white;
            border-left: none;
            border-right: 1px solid #aaaaaa;
            border-bottom: none;
            text-decoration: none;
            background-color: #bbbbbb;
            text-align: center;
            padding: 0.75em 0.25em 0 0.25em;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            MultiView and View Control Test</h1>
        <asp:MultiView ID="mviewMain" runat="Server" ActiveViewIndex="0">
            <asp:View ID="CustomerView" runat="Server">
                <asp:Panel ID="panelNavigatonView1" runat="server" CssClass="TabContainer">
                    <asp:Label ID="labOne" runat="Server" CssClass="TabItemActive" Text="Customer Information" />
                    <asp:LinkButton ID="lnkb_DefaultBook" CssClass="TabItemInactive" Text="Customer Book Selections"
                        runat="Server" OnCommand="LinkButton_Command" CommandName="Book" />
                    <asp:LinkButton ID="lnkb_DefaultCategories" CssClass="TabItemInactive" Text="Customer Categories"
                        runat="server" OnCommand="LinkButton_Command" CommandName="Categories" />
                </asp:Panel>
                <asp:Panel ID="panelView1" runat="server" CssClass="ContentPanel">
                    <h2>
                        Customer's Information</h2>
                    <p>
                        First Name:
                        <asp:TextBox ID="txtFirst" runat="server" /></p>
                    <p>
                        Last Name:
                        <asp:TextBox ID="txtLast" runat="server" /></p>
                    <p>
                        Phone:
                        <asp:TextBox ID="txtPhone" runat="server" /></p>
                    <asp:Button ID="view1Next" runat="Server" Width="6em" Text="Next" CommandName="NextView" />
                </asp:Panel>
            </asp:View>
            <asp:View ID="BookView" runat="Server">
                <asp:Panel ID="panelNavigatonView2" runat="server" CssClass="TabContainer">
                    <asp:LinkButton ID="lnkb_BookCustomer" runat="Server" CssClass="TabItemInactive"
                        Text="Customer Information" OnCommand="LinkButton_Command" CommandName="Customer" />
                    <asp:Label ID="Label3" runat="Server" CssClass="TabItemActive" Text="Customer Book Selections" />
                    <asp:LinkButton ID="lnkb_BookCategories" runat="server" CssClass="TabItemInactive"
                        Text="Customer Categories" OnCommand="LinkButton_Command" CommandName="Categories" />
                </asp:Panel>
                <asp:Panel ID="panelView2" runat="server" CssClass="ContentPanel">
                    <h2>
                        Customer's Book Selections</h2>
                    <p>
                        <em>Core JavaServer Faces</em>
                        <br />
                        Cay Horstmann, David Geary
                    </p>
                    <p>
                        <em>Patterns of Enterprise Application Architecture </em>
                        <br />
                        Martin Fowler
                    </p>
                    <asp:Button ID="view2Back" runat="Server" Text="Previous" CommandName="PrevView"
                        Width="6em" />
                    <asp:Button ID="view2Next" runat="Server" Text="Next" CommandName="NextView" Width="6em" />
                </asp:Panel>
            </asp:View>
            <asp:View ID="CategoriesView" runat="Server">
                <asp:Panel ID="panelNavigatonView3" runat="server" CssClass="TabContainer">
                    <asp:LinkButton ID="lnkb_CategoriesCustomer" runat="Server" CssClass="TabItemInactive"
                        Text="Customer Information" OnCommand="LinkButton_Command" CommandName="Customer" />
                    <asp:LinkButton ID="lnkb_CategoriesBook" runat="Server" CssClass="TabItemInactive"
                        Text="Customer Book Selections" OnCommand="LinkButton_Command" CommandName="Book" />
                    <asp:Label ID="Label4" runat="Server" CssClass="TabItemActive" Text="Customer Categories" />
                </asp:Panel>
                <asp:Panel ID="panelView3" runat="server" CssClass="ContentPanel">
                    <h2>
                        Customer Categories</h2>
                    <p>
                        Programming</p>
                    <p>
                        Object Technologies</p>
                    <asp:Button ID="view3Prev" runat="Server" Text="Previous" CommandName="PrevView"
                        Width="6em" />
                    <asp:Button ID="view3First" runat="Server" Text="Start" CommandName="SwitchViewByIndex"
                        CommandArgument="0" Width="6em" />
                </asp:Panel>
            </asp:View>
        </asp:MultiView>
    </div>
    </form>
</body>
</html>

MultiViewTest.aspx.cs

public partial class MultiViewTestaspx : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // The first time the page loads, render the DefaultView.
        if (!IsPostBack)
        {
            // Set CustomerView as the default view
            mviewMain.SetActiveView(CustomerView);
        }
    }
    protected void LinkButton_Command(object sender, CommandEventArgs e)
    {
        // Determine which link button was clicked and set the
        // active view to the view selected by the user
        switch ((string)e.CommandName)
        {
            case "Customer":
                mviewMain.SetActiveView(CustomerView);
                break;
            case "Book":
                mviewMain.SetActiveView(BookView);
                break;
            case "Categories":
                mviewMain.SetActiveView(CategoriesView);
                break;
        }
    }
}

5、Wizard Control

5.1 属性

5.2 对象模型

5.3 一些重要的属性

5.4 理解Wizard外观设置的一些属性

Style elements are used to specify the font, border, color, size, or CSS class of the wizard part referenced by the style element.

Template elements are used to define a custom layout for a given element.

5.5 样式和模版的设置

5.5.1 Header Area的设置

Style:

<asp:Wizard ID="myWizard" runat="server" HeaderText="Checkout">
<HeaderStyle BackColor="#CC9966" Font-Bold="true"
Font-Size="Large"/>
</asp:Wizard>
or
<asp:Wizard ID="myWizard" runat="server" HeaderText="Checkout"
HeaderStyle-BackColor="#CC9966" HeaderStyle-Font-Bold="true"
HeaderStyle-Font-Size="Large">
</asp:Wizard>

Template:

<asp:Wizard ID="myWizard" runat="server"
HeaderText="Checkout">
<HeaderTemplate>
<div style="margin: 5px 5px 5px 5px">
<i><%= myWizard.HeaderText %>
Step <%= myWizard.ActiveStepIndex+1 %> of 2</i><br />
<b><%= myWizard.ActiveStep.Title%></b>
</div>
</HeaderTemplate>
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server"
Title="Login">

5.6 事件处理器Wizard Event Handling

5.6.1 事件

5.6.1.1 NextButtonClick Event Handler

protected void myWizard_NextButtonClick(object sender,
WizardNavigationEventArgs e)
{
if (myWizard.ActiveStep == WizardStep1)
{
string email = txtEmail.Text;
string passwd = txtPassword.Text;
// Check database to see if this user exists
bool okay = UserBusObject.CheckIfOkay(email, passwd);
if ( ! okay )
{
myLabel.Text += "User does not exist<br/>";
// Cancel the move to the next wizard step
e.Cancel = true;
}
}
else if (myWizard.ActiveStep == WizardStep2)
{
// Validation for step 2 goes here
}
// etc
}

5.6.1.2 ActiveStepChanged Event Handler

protected void myWizard_ActiveStepChanged(object sender, EventArgs e)
{
     // If we are on the first step, then …
    if (myWizard.ActiveStep == WizardStep1)
        {
             // … check the database to see if we need to
            // enter an address
         if ( UserBusObject.NeedAddress( txtEmail.Text,txtPassword.Text) )
             {
                  myWizard.MoveTo(WizardStep2);
              }
        else
        {
             myWizard.MoveTo(WizardStep3);
        }
}
}

5.6.1.3 FinishButtonClick Event Handler

protected void myWizard_FinishButtonClick(object sender,
WizardNavigationEventArgs e)
{
// Gather the data from the various steps
string email = txtEmail.Text;
// Gather the data from the various steps
// Now fill the content of the confirmation wizard step
myLabel.Text += "FinishButtonClick called<br/>";
Label labConfirm =
(Label)myWizard.FindControl("labConfirmation");
labConfirm.Text = "Order has been processed for " +
txtEmail.Text;
}

6、FileUpload Control

6.1 属性

7、PlaceHolder Control

8、综合示例Creating a File Browser

FileBrowser.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileBrowser.aspx.cs" Inherits="FileBrowser" %>
 
<!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></title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1 class="boxes">
            Files on the Server:
            <asp:Literal ID="litLocation" runat="server" />
        </h1>
        <asp:Panel ID="panFiles" runat="server" CssClass="boxes">
            <asp:PlaceHolder ID="myPlaceHolder" runat="server" />
        </asp:Panel>
        <asp:Panel ID="Panel1" runat="server" CssClass="boxes">
            <asp:TextBox ID="txtFolder" runat="server"></asp:TextBox>
            <asp:Button ID="btnNewFolder" runat="server" Text="Create New Folder" OnClick="btnNewFolder_Click" />
        </asp:Panel>
        <asp:Panel ID="panUpload" runat="server" CssClass="boxes">
            Choose a file to upload to the server<br />
            <asp:FileUpload ID="fupTest" runat="server" Width="400px" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" />
            <p>
                <asp:Label ID="labMessage" runat="server"></asp:Label>
            </p>
        </asp:Panel>
    </div>
    </form>
</body>
</html>

FileBrowser.aspx.cs

   1:  using System;
   2:  using System.Web.UI;
   3:  using System.Web.UI.WebControls;
   4:  using System.IO;
   5:   
   6:  /// <summary>
   7:  /// Web Form that allows user to view/download files on the
   8:  /// server. User can also upload files and create folders.
   9:  /// </summary>
  10:  public partial class FileBrowser : System.Web.UI.Page
  11:  {
  12:      /// <summary>
  13:      /// Retrieve the path of folder and generate the file listing
  14:      /// </summary>
  15:      protected void Page_Load(object sender, EventArgs e)
  16:      {
  17:          string currentRoot = RetrievePathOfFolderToDisplay();
  18:          litLocation.Text = currentRoot;
  19:          GenerateListing(currentRoot);
  20:      }
  21:      /// <summary>
  22:      /// Displays the content of the specified folder.
  23:      /// </summary>
  24:      private void GenerateListing(string rootpath)
  25:      {
  26:          // First clear out the place holder
  27:          myPlaceHolder.Controls.Clear();
  28:          // Calculate the path to retrieve folders + files
  29:          string path = Server.MapPath("") + "/" + rootpath;
  30:          // Make the "go up a level" link if needed
  31:          MakeUpOneLevelLink(rootpath);
  32:          // Get a list of all folders
  33:          DirectoryInfo dirInfo = new DirectoryInfo(path);
  34:          DirectoryInfo[] folders = dirInfo.GetDirectories();
  35:          // Loop through each folder and display it
  36:          foreach (DirectoryInfo folder in folders)
  37:          {
  38:              DisplayFolder(folder, rootpath);
  39:          }
  40:          // Get a list of all the files in current path
  41:          FileInfo[] files = dirInfo.GetFiles();
  42:          // Loop through each file
  43:          foreach (FileInfo file in files)
  44:          {
  45:              DisplayFile(file, rootpath);
  46:          }
  47:      }
  48:      /// <summary>
  49:      /// Retrieves the path of the folder to be displayed
  50:      /// </summary>
  51:      private string RetrievePathOfFolderToDisplay()
  52:      {
  53:          string localpath = Request.QueryString["local"];
  54:          // If no query string, use uploads folder as the root
  55:          if (localpath == null)
  56:              return "uploads";
  57:          else
  58:              // Remove the URL encoding necessary for
  59:              // the querystring
  60:              return Server.UrlDecode(localpath);
  61:      }
  62:      /// <summary>
  63:      /// Displays the appropriate controls for the passed folder
  64:      /// </summary>
  65:      private void DisplayFolder(DirectoryInfo folder,
  66:      string rootpath)
  67:      {
  68:          // Get the folder name without the path
  69:          string shortfolder = Path.GetFileName(folder.FullName);
  70:          // Add a folder icon
  71:          Image img = new Image();
  72:          img.ImageUrl = "images/mime_folder.gif";
  73:          myPlaceHolder.Controls.Add(img);
  74:          // Add a nonbreakable space
  75:          LiteralControl space1 = new LiteralControl("&nbsp;");
  76:          myPlaceHolder.Controls.Add(space1);
  77:          // Add a link to the folder so user can display it
  78:          HyperLink lnk = new HyperLink();
  79:          lnk.Text = shortfolder;
  80:          // The link for the folder must pass the folder name.
  81:          // Because the folder name may contain characters that are
  82:          // not allowed in a querystring, we must URL encode it
  83:          lnk.NavigateUrl = "FileBrowser.aspx?local=" +
  84:          Server.UrlEncode(rootpath + "/" + shortfolder);
  85:          myPlaceHolder.Controls.Add(lnk);
  86:          // Add a line break
  87:          LiteralControl br1 = new LiteralControl("<br/>");
  88:          myPlaceHolder.Controls.Add(br1);
  89:      }
  90:      /// <summary>
  91:      /// Displays the appropriate controls for the passed file
  92:      /// </summary>
  93:      private void DisplayFile(FileInfo file, string rootpath)
  94:      {
  95:          // Get the filename without the path
  96:          string shortname = Path.GetFileName(file.FullName);
  97:          // Add a file icon
  98:          Image img = new Image();
  99:          img.ImageUrl = GetIconForExtension(file);
 100:          myPlaceHolder.Controls.Add(img);
 101:          // Add a nonbreakable space
 102:          LiteralControl space2 = new LiteralControl("&nbsp;");
 103:          myPlaceHolder.Controls.Add(space2);
 104:          // Add a link to the file so user can download/view it
 105:          HyperLink lnk = new HyperLink();
 106:          lnk.Text = shortname;
 107:          lnk.NavigateUrl = Server.UrlDecode(rootpath) + "/" +
 108:          shortname;
 109:          myPlaceHolder.Controls.Add(lnk);
 110:          // Add the file size in kb
 111:          long kb = file.Length / 1000;
 112:          LiteralControl size = new LiteralControl(" [" + kb +
 113:          " KB]");
 114:          myPlaceHolder.Controls.Add(size);
 115:          // Add a line break
 116:          LiteralControl br2 = new LiteralControl("<br/>");
 117:          myPlaceHolder.Controls.Add(br2);
 118:      }
 119:      /// <summary>
 120:      /// Returns the filename of the appropriate icon image file
 121:      /// based on the extension of the passed file
 122:      /// </summary>
 123:      private string GetIconForExtension(FileInfo file)
 124:      {
 125:          string image = "images/";
 126:          string ext = Path.GetExtension(file.FullName).ToLower();
 127:          if (ext == ".txt")
 128:              image += "mime_text.gif";
 129:          else if (ext == ".doc")
 130:              image += "mime_doc.gif";
 131:          else if (ext == ".pdf")
 132:              image += "mime_pdf.gif";
 133:          else if (ext == ".gif" || ext == ".jpg" || ext == ".wmf")
 134:              image += "mime_image.gif";
 135:          else if (ext == ".html" || ext == ".htm")
 136:              image += "mime_html.gif";
 137:          else
 138:              image += "mime_unknown.gif";
 139:          return image;
 140:      }
 141:      /// <summary>
 142:      /// Makes the "go up a level" link (if needed for the
 143:      /// current folder) and adds it to the place holder
 144:      /// </summary>
 145:      private void MakeUpOneLevelLink(string currentFolder)
 146:      {
 147:          // Get the previous folder (the next one "up" in
 148:          // the hierarchy)
 149:          string previousFolder = GetPreviousFolder(currentFolder);
 150:          // If there is a previous path, add a link to
 151:          // place holder
 152:          if (previousFolder != "")
 153:          {
 154:              Image imgBack = new Image();
 155:              imgBack.ImageUrl = "images/mime_folder.gif";
 156:              myPlaceHolder.Controls.Add(imgBack);
 157:              HyperLink lnkBack = new HyperLink();
 158:              lnkBack.Text = "..";
 159:              lnkBack.NavigateUrl = "FileBrowser.aspx?local=" +
 160:              Server.UrlEncode(previousFolder);
 161:              myPlaceHolder.Controls.Add(lnkBack);
 162:              LiteralControl br = new LiteralControl("<br/>");
 163:              myPlaceHolder.Controls.Add(br);
 164:          }
 165:      }
 166:      /// <summary>
 167:      /// Gets the previous folder (the next one "up" in the file
 168:      /// system hierarchy) from the passed path.
 169:      /// If there was no previous folder, return an
 170:      /// empty string
 171:      /// </summary>
 172:      private string GetPreviousFolder(string path)
 173:      {
 174:          int posOfLastSlash = path.LastIndexOf("/");
 175:          if (posOfLastSlash < 0)
 176:              return "";
 177:          string stripped = path.Remove(posOfLastSlash);
 178:          return stripped;
 179:      }
 180:      /// <summary>
 181:      /// Event handler for the upload button for the FileUploader
 182:      /// </summary>
 183:      protected void btnUpload_Click(object sender, EventArgs e)
 184:      {
 185:          // The location for the uploaded file is current path
 186:          string path = RetrievePathOfFolderToDisplay();
 187:          if (fupTest.HasFile)
 188:          {
 189:              string fullname = Server.MapPath(path + "/" +
 190:              fupTest.FileName);
 191:              if (System.IO.File.Exists(fullname))
 192:              {
 193:                  labMessage.Text =
 194:                  "File already exists - uploaded cancelled";
 195:              }
 196:              else
 197:              {
 198:                  fupTest.SaveAs(fullname);
 199:                  labMessage.Text = "File successfully uploaded";
 200:                  // Recreate the file listing to show the
 201:                  // uploaded file
 202:                  GenerateListing(path);
 203:              }
 204:          }
 205:          else
 206:          {
 207:              labMessage.Text = "File was not specified";
 208:          }
 209:      }
 210:      /// <summary>
 211:      /// Event handler for the create new folder button
 212:      /// </summary>
 213:      protected void btnNewFolder_Click(object sender, EventArgs e)
 214:      {
 215:          // Get the location for the new folder
 216:          string folderLocation = RetrievePathOfFolderToDisplay();
 217:          string fullPath = Server.MapPath(folderLocation) + "/" +
 218:          txtFolder.Text;
 219:          // Create the folder on the server
 220:          Directory.CreateDirectory(fullPath);
 221:          // Recreate the file listing to show the new folder
 222:          GenerateListing(folderLocation);
 223:      }
 224:  }

运行效果:

9、AdRotator Control

9.1 属性

10、Xml Control

10.1 属性

10.2 XML控件的编程

10.2.1 Processing an RSS Feed

RssTransform1.xsl

<?xml version="1.0" encoding="utf-8"?>
 
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 
    <xsl:template match="/rss/channel">
        <h2 style="font: 14pt Verdana; font-weight: bold; color: #827753; background-color: #CFBD84;">
            <xsl:value-of select="title" />
        </h2>
        <p style="font: 10pt Verdana, Helvetica; margin-bottom: 10px;">
            <xsl:value-of select="description" />
        </p>
        <xsl:for-each select="item">
            <h3 style="font: 12pt Verdana, Helvetica; border-bottom: 1px solid #A89A6C;">
                <xsl:value-of select="title" />
            </h3>
            <p style="font: 10pt Verdana, Helvetica;">
                <xsl:value-of select="description" />
                <br/>
                <a href="{link}">
                    Read more
                </a>
            </p>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
 

RssTransform2.xsl

<?xml version="1.0" encoding="utf-8"?>
 
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 
<xsl:template match="/rss/channel">
  <div style="width: 300px; position: absolute; left: 350px; top: 12px; background-color: #DFDFDF; padding: 10px; color: #606060; font: Trebuchet MS, Times New Roman, serif;">
    <div style="text-transform: uppercase;">
      <p style="font-size: 22px; color: #930000; margin-bottom: 2px;">
        <xsl:value-of select="title" />
      </p>
      <p style="font-size: 11px; ">
        <xsl:value-of select="description" />
      </p>
    </div>
    <xsl:for-each select="item">
      <div style="background-color: #D1D1D1; padding: 2px; margin-top: 8px;">
        <p style="margin-bottom: 1px; margin-top: 1px; font-size: 16px;">
          <a href="{link}" style=" color: #930000;">
          <xsl:value-of select="title" />
          </a>
        </p>
        <p style="font-size: 10px; margin-top: 1px; margin-bottom: 1px; border-bottom: 1px dashed #949494;">
          <xsl:value-of select="pubDate" />        
        </p>
        <p style="font: 11px Verdana, sans-serif; line-height: 18px; margin-top: 1px; margin-bottom: 1px;">
          <xsl:value-of select="description" />          
        </p>
      </div>
    </xsl:for-each>
  </div>
</xsl:template>
</xsl:stylesheet> 
 

RssReader.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RssReader.aspx.cs" Inherits="RssReader" %>
 
<!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>Rss Reader</title>
    <link href="chapterStyles.css" type="text/css" rel="stylesheet" />
    <style type="text/css">
        .SelectArea
        {
            padding: 5px;
            width: 300px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Panel ID="panSelect" runat="server" BorderWidth="1" BorderStyle="Solid" BackColor="Beige"
        CssClass="SelectArea">
        <h1>
            RSS Reader</h1>
        <p>
            Select a RSS feed<br />
            <asp:DropDownList ID="drpFeeds" runat="server">
                <asp:ListItem Value="http://rss.cnn.com/rss/cnn_topstories.rss">CNN</asp:ListItem>
                <asp:ListItem Value="http://msdn.microsoft.com/rss.xml">MSDN</asp:ListItem>
                <asp:ListItem Value="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/technology/rss.xml">BBC Technology News</asp:ListItem>
            </asp:DropDownList>
        </p>
        <p>
            Select a template<br />
            <asp:DropDownList ID="drpTemplates" runat="server">
                <asp:ListItem Value="~/App_Data/RssTransform1.xsl">RssTransform 1</asp:ListItem>
                <asp:ListItem Value="~/App_Data/RssTransform2.xsl">RssTransform 2</asp:ListItem>
            </asp:DropDownList>
        </p>
        <p>
            <asp:Button ID="btnRead" runat="server" Text="Read Feed" OnClick="btnRead_Click" />
        </p>
    </asp:Panel>
    <asp:Panel ID="panFeed" runat="server">
        <asp:Xml ID="myXml" runat="server"></asp:Xml>
    </asp:Panel>
    </form>
</body>
</html>

RssReader.aspx.cs

   1:  using System;
   2:   
   3:  using System.Xml.XPath;
   4:   
   5:  public partial class RssReader : System.Web.UI.Page
   6:  {
   7:      protected void Page_Load(object sender, EventArgs e)
   8:      {
   9:   
  10:      }
  11:   
  12:      protected void btnRead_Click(object sender, EventArgs e)
  13:      {
  14:          // create the XPathNavigator object
  15:          string xmlUrl = drpFeeds.SelectedValue;
  16:          XPathDocument xpdoc = new XPathDocument(xmlUrl);
  17:          XPathNavigator xnav = xpdoc.CreateNavigator();
  18:   
  19:          // setup the xml control
  20:          myXml.XPathNavigator = xnav;
  21:   
  22:          string xslFilename = drpTemplates.SelectedValue;
  23:          myXml.TransformSource = xslFilename;
  24:      }
  25:  }

运行效果

11、关键概念


posted on 2009-05-18 18:05  虎克  阅读(566)  评论(0)    收藏  举报