ASP.Net Web开发基础 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

一个Web Forms应用

下面是一个简单的web应用


Web Form结构图
//WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </div>
    </form>
</body>

WebForm1.aspx是前台的展示页面,通过CodeBehind="WebForm1.aspx.cs"指定了事件处理代码隐藏文件。

//WebForm1.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
        Response.Write("Hello,World!");
        }
    }
}

WebForm1.aspx.cs是代码隐藏文件,其中主要完成页面的加载和相关的事件处理。每个Web Form都派生至Page类,并继承这个类公开的属性和方法。Page类位于System.Web.UI命名空间中,所以要通过using System.Web.UI来进行引用。

//WebForm1.aspx.designer.cs
namespace WebApplication2 
{      
    public partial class WebForm1 
    {
        /// IDE自动生成的字段。
        protected global::System.Web.UI.HtmlControls.HtmlForm form1;
        protected global::System.Web.UI.WebControls.Button Button1;
    }
}

WebForm1.aspx.designer.csWebForm1.aspx.cs,共同完成了WebForm1类的定义。由于WebForm1.aspx.designer.cs中的代码主要完成页面服务器控件的声明,是由IDE自动生成,不宜与事件处理代码WebForm1.aspx.cs混在一起,所以通过partial关键字将WebForm1类的具体实现,分别放在了两个不同的.cs文件中。

查看WebForm1.aspx、WebForm1.aspx.designer.cs、WebForm1.aspx.cs,修改程序的代码,体会和理解设计、代码分离机制。