Fork me on GitHub

asp.net初学习实现简单的增删改查功能

    在学习中发现网页模板可以大大节约重复的页面代码,同时对于WebSite开发的程序在不同的页面直接调用已写好的代码既不方面,只是作为代码量不大的程序进行开发还是比较方便。

    get和post的区别get是通过url传递表单值,post通过url看不到表单域的值;get传递的数据量是有限的,如果要传递大数据量不能用get,比如上传文章、传递密码或者<textarea>发表大段文章,post则没有这个限制;post会有浏览器提示重新提交表单的问题。也就是说get和post都是以不同的方式提交表单的信息,只是方式不一样,post是以头报文的形式传递,我们可以使用火狐的免费插件firebug或者免费的httpwatch(破解版的当然免费),看到这些。

    简单的说浏览器和服务器直接就是请求和回应,内部的具体细节可以看看博客园中的很多示例图,当然我们可以分析一下,就是浏览器通过DNS解析后向服务器发送请求,服务端侦听到客户端(浏览器)请求,开始分配相应套接字并建立连接,之后就是一方发送一方接收回应的过程,这里面存在一个长连接短连接的概念,具体还是查资料,这里就不多说了。

    现在我们先来分析一下已经生成好的web程序,我们来反编译看下具体的执行过程。

我们只看其中关键的部分,也是我们一般程序中的主体部分,使用reflector

 1 [CompilerGlobalScope]
 2 public class default_aspx : _Default, IHttpHandler
 3 {
 4     // Fields
 5     private static object __fileDependencies;
 6     private static bool __initialized;
 7 
 8     // Methods
 9     [DebuggerNonUserCode]
10     public default_aspx();
11     [DebuggerNonUserCode]
12     private HtmlHead __BuildControl__control2();
13     [DebuggerNonUserCode]
14     private HtmlTitle __BuildControl__control3();
15     [DebuggerNonUserCode]
16     private HtmlForm __BuildControlform1();
17     [DebuggerNonUserCode]
18     private void __BuildControlTree(default_aspx __ctrl);
19     [DebuggerNonUserCode]
20     protected override void FrameworkInitialize();
21     [DebuggerNonUserCode]
22     public override int GetTypeHashCode();
23     [DebuggerNonUserCode]
24     public override void ProcessRequest(HttpContext context);
25 }
26 
27  
28 Expand Methods
29  

它对应的源代码如下:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <title>测试</title>
 8 </head>
 9 <body>
10     <form id="form1" runat="server">
11     <div>
12     
13     </div>
14     </form>
15 </body>
16 </html>

现在我们再来看关键的部分:

 

 1 [DebuggerNonUserCode]
 2 private void __BuildControlTree(default_aspx __ctrl)
 3 {
 4     this.InitializeCulture();
 5     IParserAccessor accessor = __ctrl;
 6     accessor.AddParsedSubObject(new LiteralControl("\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n"));
 7     HtmlHead head = this.__BuildControl__control2();
 8     accessor.AddParsedSubObject(head);
 9     accessor.AddParsedSubObject(new LiteralControl("\r\n<body>\r\n    "));
10     HtmlForm form = this.__BuildControlform1();
11     accessor.AddParsedSubObject(form);
12     accessor.AddParsedSubObject(new LiteralControl("\r\n</body>\r\n</html>\r\n"));
13 }

从上面可以看出,.NET运行时将html创建成一个树对象,而后已以创建节点对象模型

 

1 [DebuggerNonUserCode]
2 private HtmlTitle __BuildControl__control3()
3 {
4     HtmlTitle title = new HtmlTitle();
5     IParserAccessor accessor = title;
6     accessor.AddParsedSubObject(new LiteralControl("测试"));
7     return title;
8 }

这里我只是让大家能看到 <title>测试</title>的效果,具体的可以自己看看。

下面就写个小代码试下手感受下asp.net web开发,基本原理都差不多只是对于刚从Winform转过来的同学感觉上很繁琐,节约时间不多说了,直接上代码,代码简单就是为了自己熟悉测试的

 

 1 <%@ WebHandler Language="C#" Class="List" %>
 2 
 3 using System;
 4 using System.Web;
 5 using System.Data;
 6 using System.Data.SqlClient;
 7 
 8 public class List : IHttpHandler {
 9     
10     public void ProcessRequest (HttpContext context) {
11         context.Response.ContentType = "text/html";
12         DataTable dt = SqlHelper.ExecuteDataTble();
13         System.Text.StringBuilder sb = new System.Text.StringBuilder();
14         foreach (DataRow dr in dt.Rows)
15         {
16             sb.AppendLine(" <tr>");
17             sb.AppendLine("<td>" + dr["s_no"] + "</td>");
18             sb.AppendLine("<td>" + dr["s_name"] + "</td>");
19             sb.AppendLine("<td>" + dr["s_sex"] + "</td>");
20             sb.AppendLine("<td>" + dr["s_birthday"] + "</td>");
21             sb.AppendLine("<td>" + dr["s_avgrade"] + "</td>");
22             sb.AppendLine("<td>" + dr["s_dept"] + "</td>");
23             sb.AppendLine("<td><a href=del.ashx?id="+dr["s_no"]+">删除</td>");
24             sb.AppendLine("<td><input type='checkbox' name='ckdel' value= '"+ dr["s_no"]+"'/>选择</td>");
25             sb.AppendLine("<td><a href='UpdateRecord.ashx'>修改</td>");
26             sb.AppendLine("<tr>");
27         }
28         string content = System.IO.File.ReadAllText(context.Server.MapPath("model.htm"));
29         content = content.Replace("@replace", sb.ToString()).Replace("@title", "学生信息表");
30         context.Response.Write(content);
31     }
32  
33     public bool IsReusable {
34         get {
35             return false;
36         }
37     }
38 
39 }
40 public class SqlHelper
41 {
42     public static System.Data.DataTable ExecuteDataTble()
43     {
44         using (SqlConnection con = new SqlConnection("Data Source=ROHELM-PC;Initial Catalog=T-SQL练手;Integrated Security=True"))
45         {
46             using (SqlCommand cmd = con.CreateCommand())
47             {
48                 cmd.CommandText = "select * from student";
49                 DataTable dt = new DataTable();
50                 SqlDataAdapter da = new SqlDataAdapter(cmd);
51                 da.Fill(dt);
52                 return dt;
53             }
54         }
55     }
56 }

下面这个其实保存的形式是什么无关紧要的,只要是文本形式就行。

model
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5     <style type="text/css">
 6         table
 7         {
 8             background-color: Yellow;
 9             border-color: Black;
10             border-spacing: 0;
11             border-style: dotted;
12             border-width: medium;
13         }
14     </style>
15 </head>
16 <body>
17     <fieldset title="增删改查测试">
18         <form action="del.ashx" method="post">
19         <table border="1">
20             <thead>
21                 <tr>
22                     @title</tr>
23             </thead>
24             <tbody>
25                 @replace
26                 <tr>
27                     <td colspan="6">
28                         <center>
29                             <input type="submit" value="批量删除" />
30                          </center>
31                     </td>
32                     <td colspan="2">
33                       <a href="addRecord.htm">添加记录</a> 
34                     </td>
35                 </tr>
36             </tbody>
37         </table>
38         </form>
39     </fieldset>
40 </body>
41 </html>

删除部分

del
 1 <%@ WebHandler Language="C#" Class="del" %>
 2 
 3 using System;
 4 using System.Web;
 5 using System.Data.SqlClient;
 6 using System.IO;
 7 public class del : IHttpHandler {
 8     public void ProcessRequest (HttpContext context) {
 9         string tooglePage = File.ReadAllText(context.Server.MapPath("jumpPage.htm"));
10         context.Response.ContentType = "text/html";
11         //通过url传参数
12         string id = context.Request.QueryString["id"];
13         string ids = context.Request.Form["ckdel"];
14         if (!string.IsNullOrEmpty(id))
15         {
16             SQLhelper.ExecuteNonQuery2("delete from student where s_no=@id",
17                 new SqlParameter("@id", id)
18                 );
19             tooglePage = tooglePage.Replace("@targetPage", "List.ashx");
20             context.Response.Write(tooglePage);
21         }
22         else if (!string.IsNullOrEmpty(ids))
23         {
24             SQLhelper.ExecuteNonQuery2("delete from student where s_no in (" + ids + ")");
25             tooglePage = tooglePage.Replace("@targetPage", "List.ashx");
26             context.Response.Write(tooglePage);
27         }
28         else
29         {
30        
31             context.Response.Write("删除不成功!");
32         }
33     }
34  
35     public bool IsReusable {
36         get {
37             return false;
38         }
39     }
40 
41 }
42 public partial class SQLhelper
43 {
44     public static void ExecuteNonQuery2(string sql, params SqlParameter[] paramseter)
45     {
46         using (SqlConnection con = new SqlConnection("Data Source=ROHELM-PC;Initial Catalog=T-SQL练手;Integrated Security=True"))
47         {
48             con.Open();
49             {
50                 using (SqlCommand cmd = con.CreateCommand())
51                 {
52                     cmd.CommandText = sql;
53                     cmd.Parameters.AddRange(paramseter);
54                     cmd.ExecuteNonQuery();
55                 }
56             }
57         }
58     }
59 }

添加部分

add
 1 <%@ WebHandler Language="C#" Class="ADD"%>
 2 
 3 using System;
 4 using System.Web;
 5 using System.Data.SqlClient;
 6 
 7 public class ADD : IHttpHandler {
 8     
 9     public void ProcessRequest (HttpContext context) {
10         context.Response.ContentType = "text/html";
11         string s_name=context.Request.Form["Name"];
12         string s_no = context.Request.Form["num"];
13                 SQLhelper.ExecuteNonQuery("insert into student(s_no,s_name)values(@number,@name)",
14                        new SqlParameter("number", s_no),
15                        new SqlParameter("name", s_name)
16                       );
17             context.Response.Redirect("List.ashx");
18     }
19  
20     public bool IsReusable {
21         get {
22             return false;
23         }
24     }
25 
26 }
27  public partial class SQLhelper
28 {
29      public static void ExecuteNonQuery(string sql, params SqlParameter[] paramseter)
30      {
31          using (SqlConnection con = new SqlConnection("Data Source=ROHELM-PC;Initial Catalog=T-SQL练手;Integrated Security=True"))
32          {
33              con.Open();
34              {
35                  using (SqlCommand cmd = con.CreateCommand())
36                  {
37                      cmd.CommandText = sql;
38                      cmd.Parameters.AddRange(paramseter);
39                      cmd.ExecuteNonQuery();
40                  }
41              }
42          }
43      }
44 }

使用数据库脚本:

SQL
 1 USE [T-SQL练手]
 2 GO
 3 /****** Object:  Table [dbo].[student]    Script Date: 05/10/2012 00:05:40 ******/
 4 SET ANSI_NULLS ON
 5 GO
 6 SET QUOTED_IDENTIFIER ON
 7 GO
 8 SET ANSI_PADDING ON
 9 GO
10 CREATE TABLE [dbo].[student](
11     [s_no] [int] NOT NULL,
12     [s_name] [nvarchar](50) NOT NULL,
13     [s_sex] [char](2) NULL,
14     [s_birthday] [smalldatetime] NULL,
15     [s_speciality] [varchar](50) NULL,
16     [s_avgrade] [numeric](3, 1) NULL,
17     [s_dept] [varchar](50) NULL,
18  CONSTRAINT [PK__student__2F36BC5B7F60ED59] PRIMARY KEY CLUSTERED 
19 (
20     [s_no] ASC
21 )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
22 ) ON [PRIMARY]
23 GO
24 SET ANSI_PADDING OFF
25 GO
26 /****** Object:  Default [DF__student__s_speci__03317E3D]    Script Date: 05/10/2012 00:05:40 ******/
27 ALTER TABLE [dbo].[student] ADD  CONSTRAINT [DF__student__s_speci__03317E3D]  DEFAULT ('计算机软件与理论') FOR [s_speciality]
28 GO
29 /****** Object:  Default [DF__student__s_dept__0519C6AF]    Script Date: 05/10/2012 00:05:40 ******/
30 ALTER TABLE [dbo].[student] ADD  CONSTRAINT [DF__student__s_dept__0519C6AF]  DEFAULT ('计算机科学系') FOR [s_dept]
31 GO
32 /****** Object:  Check [CK__student__s_avgra__0425A276]    Script Date: 05/10/2012 00:05:40 ******/
33 ALTER TABLE [dbo].[student]  WITH CHECK ADD  CONSTRAINT [CK__student__s_avgra__0425A276] CHECK  (([s_avgrade]>=(0) AND [s_avgrade]<=(100)))
34 GO
35 ALTER TABLE [dbo].[student] CHECK CONSTRAINT [CK__student__s_avgra__0425A276]
36 GO
37 /****** Object:  Check [CK__student__s_birth__023D5A04]    Script Date: 05/10/2012 00:05:40 ******/
38 ALTER TABLE [dbo].[student]  WITH CHECK ADD  CONSTRAINT [CK__student__s_birth__023D5A04] CHECK  (([s_birthday]>='1970-1-1' AND [s_birthday]<='2000-1-1'))
39 GO
40 ALTER TABLE [dbo].[student] CHECK CONSTRAINT [CK__student__s_birth__023D5A04]
41 GO
42 /****** Object:  Check [CK__student__s_sex__014935CB]    Script Date: 05/10/2012 00:05:40 ******/
43 ALTER TABLE [dbo].[student]  WITH CHECK ADD  CONSTRAINT [CK__student__s_sex__014935CB] CHECK  (([s_sex]='' OR [s_sex]=''))
44 GO
45 ALTER TABLE [dbo].[student] CHECK CONSTRAINT [CK__student__s_sex__014935CB]
46 GO

运行效果:

 其他操作显示区域没有调整好,且受到上传图片的限制未演示。

posted @ 2012-05-09 23:58  Halower  阅读(12627)  评论(0编辑  收藏  举报