1. 程式人生 > 實用技巧 >ASP.NET學習筆記三

ASP.NET學習筆記三

1、控制元件的屬性和方法

屬性

描述

ClientID

返回控制元件在瀏覽器端生成的識別符號

Controls

返回當前控制元件的子控制元件集合

EnableViewState

返回或設定當前控制元件是否使用檢視狀態功能

ID

返回或設定當前控制元件在頁面中的唯一標識

Page

返回當前頁面的父頁面引用

Parent

返回當前控制元件父控制元件的引用,即其所在的容器控制元件

Visible

返回或設定當前控制元件是否呈現在頁面中

2、單選按鈕與複選框

3、控制權轉移控制元件

<h3>控制權轉移控制元件</h3>
        <asp:Button ID="btn1" runat="server" Text="普通按鈕" PostBackUrl="~/server.aspx" CommandArgument="hello" />
        <asp:LinkButton ID="lbtn2" runat="server" Text="超連結按鈕" PostBackUrl="~/server.aspx" CommandArgument="hello"/>
        <asp:ImageButton ID="
imgbtn3" runat="server" ImageUrl="~/images/regist.gif" PostBackUrl="~/server.aspx" CommandArgument="hello" /> <br /> <%-- 僅僅是轉換成普通的超連結a標籤,不能提交 表單和跨頁提交資料--%> <asp:HyperLink ID="hl1" runat="server" Text="普通超連結" NavigateUrl="~/server.aspx"/>
protected void Page_Load(object
sender, EventArgs e) { txt.CssClass = "txt"; //txt.Text = DateTime.Now.ToString(); hl1.Target = "_blank"; }

四、FileUpload控制元件(實現檔案的上傳和下載)

<form id="form1" runat="server" enctype="multipart/form-data">
    <div>
        頭像:<input type="file" name="uploadFile" />
        <asp:Button ID="btnupload" runat="server" Text="上傳檔案" OnClick="btnupload_Click" />
    </div>
    </form>
protected void btnupload_Click(object sender, EventArgs e)
        {
            //獲得客戶端上傳的檔案集合
            HttpFileCollection files = Request.Files;
            //獲得指定的檔案物件
            HttpPostedFile file = files[0];
            if (file.FileName == "")
            {
                Response.Write("<script>alert('請選擇檔案上傳');</script>");
                return;
            }
            //if(file.ContentLength>10*1024)
            //{
            //    Response.Write("<script>alert('上傳的檔案不能超過10KB,請壓縮後上傳');</script>");
            //    return;
            //}
            //組裝伺服器端路徑
            string serverPath = "~/uploadFolder/" + file.FileName;
            serverPath = Server.MapPath(serverPath);//上傳的路徑必須是物理路徑
            file.SaveAs(serverPath);//實現上傳
            Response.Write("<script>alert('上傳成功');</script>");
        }

後端程式碼也可以為:

protected void btnupload_Click(object sender, EventArgs e)
        {
            if(!myFile.HasFile)
            {
                Response.Write("<script>alert('請選擇檔案上傳');</script>");
                return;
            }
            HttpPostedFile file = myFile.PostedFile;
            //if (file.ContentLength > 10 * 1024)
            //{
            //    Response.Write("<script>alert('上傳的檔案不能超過10KB,請壓縮後上傳');</script>");
            //    return;
            //}
            //組裝伺服器端路徑
            string serverPath = "~/uploadFolder/" + file.FileName;
            serverPath = Server.MapPath(serverPath);//上傳的路徑必須是物理路徑
            file.SaveAs(serverPath);//實現上傳
            Response.Write("<script>alert('上傳成功');</script>");
        }

批量上傳檔案程式碼:

<form id="form1" runat="server" enctype="multipart/form-data">
    <div>
        <input type="button" name="btnaddFile" value="點選上傳" id="btnaddFile" />
         <asp:Button ID="btnuploadFile" runat="server" Text="批量上傳" OnClick="btnuploadFile_Click"  />
    </div>

    <div id="files">

    </div>

       
    </form>

    <script src="scripts/jquery.js"></script>
    <script>
        $(function () {
            var i = 1;
            $("#btnaddFile").click(function () {              

                var file = $("<input type='file' class='file' name='file" + i + "'/><br/>");
                $("#files").append(file);
                i++;
            })
        })
    </script>
protected void btnuploadFile_Click(object sender, EventArgs e)
        {
            if (Request.Files.Count == 0)            
                return;
            int count = 0;
            for(int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFile file = Request.Files[i];
                string name = file.FileName;

                if(name!="")
                {
                    string path = "~/uploadFolder/" + name;
                    path = Server.MapPath(path);

                    file.SaveAs(path);

                    count++;
                }
            }

            Response.Write("<script>alert('成功上傳" + count + "個檔案')</script>");
           
        }

5、下載檔案

<form id="form1" runat="server">
    <div>
        <asp:HyperLink ID="hlDownLoad" runat="server" Text="點選下載"/><br />

        <asp:Button ID="btnDownLoad" runat="server" Text="點選下載"  OnClick="btnDownLoad_Click"/>
    </div>
    </form>
protected void Page_Load(object sender, EventArgs e)
        {
            //下載時提代檔案的虛擬路徑或相對路徑
            //hlDownLoad.NavigateUrl = "~/uploadFolder/邏輯題.doc";
            //hlDownLoad.Text = "邏輯題.doc";

            //hlDownLoad.NavigateUrl = "~/uploadFolder/test.xlsx";
            //hlDownLoad.Text = "test.xlsx";

            //hlDownLoad.NavigateUrl = "~/uploadFolder/test.txt";
            //hlDownLoad.Text = "test.txt";

            hlDownLoad.NavigateUrl = "~/uploadFolder/book.jpg";
            hlDownLoad.Text = "book.jpg";
        }

        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            string fileName = "book.jpg";
            string path = "~/uploadFolder/" + fileName;
            path = Server.MapPath(path);
            byte[] bytes = null;
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                //建立位元組陣列緩衝區
                 bytes= new byte[fs.Length];
                //讀取檔案到位元組陣列中
                fs.Read(bytes, 0, bytes.Length);
            }
            //通知瀏覽器檔案是以附件形式下載,而不是直接開啟的
            Response.AddHeader("Content-Disposition", "attachment;Filename="+fileName);
            //將緩衝區的位元組陣列下載到本地
            Response.BinaryWrite(bytes);
            //停止當前頁的執行
            Response.End();
        }

6、droplist和listbox控制元件

<form id="form1" runat="server">
    <div>
        班級:<asp:DropDownList ID="drpClass" runat="server"
            OnSelectedIndexChanged="drpClass_SelectedIndexChanged" Width="150">             
               </asp:DropDownList>
        <br />

        學員:<asp:ListBox ID="lstStudents" runat="server" Width="150" SelectionMode="Multiple">            
           </asp:ListBox>
    </div>
    </form>
    <script src="scripts/jquery.js"></script>
    <script>
        $(function () {

            $("#drpClass").change(function () {
               var cno=$(this).val();//班級編號
               if (cno != "-99")
                   $("#form1").submit();//手動提交表單
               else
                   $("#lstStudents").get(0).options.length = 0; //清空下拉列表            
            })


        })
    </script>
private void LoadClass()
        {
           
            List<@class> lstClass = [email protected]();
            lstClass.Insert(0,new @class { className = "--請選擇班級--", classNo = "-99" });

            #region 方法1:使用Items屬性
            //foreach (var c in lstClass)
            //{
            //    ListItem item = new ListItem { Text = c.className, Value = c.classNo };
            //    drpClass.Items.Add(item);
            //}
            
            #endregion

            #region 方法2:使用DataSource屬性
            drpClass.DataSource = lstClass;//設定資料來源
            drpClass.DataTextField = "className";//顯示的屬性是資料來源中的哪個欄位或屬性
            drpClass.DataValueField = "classNo";//隱藏的屬性是資料來源中的哪個欄位或屬性
            drpClass.DataBind();//將當前控制元件的資料繫結至控制元件中,一定要呼叫
            #endregion
        }

        /// <summary>
        /// 班級下拉列表選項改變時觸發
        /// </summary>       
        protected void drpClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            string cno = drpClass.SelectedValue;//獲取當前選中班級的班級編號
            LoadStudents(cno);
           
        }
        /// <summary>
        /// 根據班級編號載入學員
        /// </summary>
        /// <param name="cno">班級編號</param>
        private void LoadStudents(string cno)
        {
            List<student> lststus = db.student.Where(s => s.classNo == cno).ToList();          

            lstStudents.DataSource = lststus;
            lstStudents.DataTextField = "sname";
            lstStudents.DataValueField = "sno";
            lstStudents.DataBind();
        }