標籤:des blog http io os 使用 ar java for
1.介紹正常情況下添加一個WebForm程式結構如下(命名為:myWebForm.aspx)
檔案說明:.aspx檔案:書寫html代碼部分,以及javascript,css等代碼書寫及引用
.aspx.cs檔案:伺服器端,使用C#代碼處理用戶端發過來的請求,做出相應的響應
.aspx.designer.cs檔案:視圖表單建立檔案,繪製在伺服器端需要的控制項,即相當於初始化的部分
現在的需求是:將.aspx.designer.cs檔案刪除,在頁面類裡面添加一個在伺服器端啟動並執行控制項Button和TextBox,當點擊Button按鈕時為TextBox賦值“Hello”,同時進行頁面登入的校正.(當刪除此檔案後,在頁面通過工具箱添加伺服器端控制項是會報錯)
所以我們要進行一系列的修改,重寫一些方法,添加綁定事件,具體實施方法如下:2.步驟1.添加兩個WebForm表單,命名為:myWebForm.aspx 和 FormBase.aspx2.在myWebForm.aspx檔案內添加兩個控制項,代碼如下[html] view plaincopy
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="myWebForm.aspx.cs" Inherits="myWebApplication.myWebForm" %>
-
- <!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>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <%--添加兩個控制項,並添加runat="server"屬性--%>
- <input id="myTxt" type="text" runat="server" />
- <input id="myBtn" type="button" value="button" runat="server" />
- </div>
- </form>
- </body>
- </html>
3.刪除檔案,將兩個表單中的.aspx.designer.cs(將裡面定義的控制項變數語句可以先複製出來)4.編輯FormBase.aspx檔案,重寫方法,代碼如下:[csharp] view plaincopy
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace myWebApplication
- {
- public partial class FormBase : System.Web.UI.Page
- {
- //所有繼承此類的頁面在開啟前都會先運行此類裡的Page_Load方法
- //更改方法的修飾符
- private void Page_Load(object sender, EventArgs e)
- {
- //do somethings
- //可以在此處進行頁面登入校正處理
- }
- //重寫OnInit
- override protected void OnInit(EventArgs e)
- {
- InitializeComponent();
- base.OnInit(e);
- }
- private void InitializeComponent()
- {
- this.Load += new System.EventHandler(this.Page_Load);
- }
- }
- }
5.編輯myWebForm.aspx,繼承FormBase,並重寫方法,為頁面類的控制項添加事件 [csharp] view plaincopy
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace myWebApplication
- {
- public partial class myWebForm : FormBase
- {
- protected System.Web.UI.HtmlControls.HtmlInputText myTxt;
- protected System.Web.UI.HtmlControls.HtmlInputButton myBtn;
-
- //重寫OnInit
- protected override void OnInit(EventArgs e)
- {
- InitializeComponent();
- base.OnInit(e);//調用父類的OnInit
- }
- //添加事件
- private void InitializeComponent()
- {
- //為頁面類的id為myBtn的Button添加事件
- this.myBtn.ServerClick += new EventHandler(myBtn_ServerClick);
- //this.Load += new System.EventHandler(this.Page_Load);
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- //頁面第一次載入時會運行裡面的方法
- //通過點擊提交表單的時候不會運行裡面的方法
- }
- }
- private void myBtn_ServerClick(object sender, EventArgs e)
- {
- //當點擊button時會觸發此事件
- string s = "Hello";
- myTxt.Value = s;
- }
- }
- }
6.效果,運行此介面,點擊button文字框會顯"Hello字樣"
7.總結
1.刪除多餘的檔案
2.通過繼承的方式對每個頁面進行登入校正
3.等等
asp.net WebForm程式刪除.designer.cs檔案之後的故事