在整理以前资料时偶尔发现有一个效果不错的Ajax留言板程序,是以前一个系统的一个部分。今天抽了点时间,将其独立成一个项目,与大家分享下,先来看下具体的效果图:

思路很简单,就是一般的Ajax系统,主要是里面的一些jQuery的特效确实不错。下面是实现步骤:

环境:Visual Studio 2010 + SQL Server 2008 + jQuery1.4.1

1. 首先设计数据库,很简单,留言人、留言时间、留言内容、头像等字段,具体的数据库表创建语句如下

 
  
  1. CREATE TABLE [dbo].[tb_message_board](  
  2.     [MSG_ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [MSG_USER] [nchar](20) NULL,  
  4.     [MSG_FACE] [nchar](50) NULL,  
  5.     [MSG_CONTENT] [nchar](100) NULL,  
  6.     [MSG_TIME] [datetime] NULL  
  7. ) ON [PRIMARY] 

大家可以在自己机器上执行该SQL ,你项目的数据库,同时要修改Web.config中的数据库名;
 

2. 创建ASP.NET 应用程序,默认已经有母版页了,我们只要添加一个使用了默认母版页的Web页面,取名为MessageBoard;
 

3. 创建一些常用的文件夹,如images文件夹,用来存放项目中使用的图片,我这边最后创建后的解决方案管理器如下图:
 

4. 使用div 及css 布局你的留言板页面,我之前参考了http://www.css88.com/demo/ajax-deleet 中的布局;
 

5. 当初为了方便起见,使用了最基础的SQL Helper作为数据操作类,下面是该 SQL Helper类的代码:

 
  
  1. /*  
  2.  * 文件名:SQLHelper  
  3.  * 说明:SQL Server帮助类  
  4.  * 作者:Alexis  
  5.  * 网站:http://alexis.blog.51cto.com/  
  6.  * 创建时间:20100428  
  7.  * */  
  8. using System;  
  9. using System.Data;  
  10. using System.Configuration;  
  11. using System.Linq;  
  12. using System.Web;  
  13. using System.Web.Security;  
  14. using System.Web.UI;  
  15. using System.Web.UI.HtmlControls;  
  16. using System.Web.UI.WebControls;  
  17. using System.Web.UI.WebControls.WebParts;  
  18. using System.Xml.Linq;  
  19. using System.Data.SqlClient;  
  20.  
  21.  
  22. /// <summary> 
  23. ///SQLHelper 的摘要说明  
  24. /// </summary> 
  25. public class SQLHelper  
  26. {  
  27.     SqlConnection conn;  
  28.  
  29.     public SQLHelper()  
  30.     {  
  31.         string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MessageBoard"].ToString();  
  32.         conn = new SqlConnection(connectionString);  
  33.     }  
  34.  
  35.     /// <summary> 
  36.     /// 执行SQL命令,将数据赋给数据集的引用  
  37.     /// </summary> 
  38.     public bool RunSQL(string cmdText, ref DataTable dt)  
  39.     {  
  40.         try  
  41.         {  
  42.             conn.Open();  
  43.             SqlCommand cmd = new SqlCommand(cmdText, conn);  
  44.             SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  45.             DataSet ds1 = new DataSet();  
  46.             sda.Fill(ds1);  
  47.             dt = ds1.Tables[0];  
  48.         }  
  49.         catch (SqlException se)  
  50.         {  
  51.             return false;  
  52.             throw new Exception(se.Message, se);  
  53.         }  
  54.         return true;  
  55.     }  
  56.  
  57.     /// <summary> 
  58.     /// 执行带参数的SQL语句  
  59.     /// </summary> 
  60.     /// <param name="cmdText"></param> 
  61.     /// <param name="sp"></param> 
  62.     public bool RunSQL(string cmdText, SqlParameter[] sp)  
  63.     {  
  64.         try  
  65.         {  
  66.             if(conn.State== ConnectionState.Closed)  
  67.                 conn.Open();  
  68.             SqlCommand cmd = new SqlCommand(cmdText, conn);  
  69.             if (sp != null)  
  70.             {  
  71.                 for (int i = 0; i < sp.Length; i++)  
  72.                 {  
  73.                     cmd.Parameters.Add(sp[i]);//将参数加到Command中  
  74.                 }  
  75.             }  
  76.             cmd.ExecuteNonQuery();  
  77.         }  
  78.         catch (SqlException se)  
  79.         {  
  80.             return false;  
  81.             throw new Exception(se.Message, se);  
  82.  
  83.         }  
  84.         finally  
  85.         {  
  86.             conn.Close();  
  87.         }  
  88.         return true;  
  89.  
  90.     }  
  91.  
  92.     public DataTable getDataTable(string cmdText)  
  93.     {  
  94.         DataTable dt = null;  
  95.         try  
  96.         {  
  97.             if (conn.State == ConnectionState.Closed)  
  98.                 conn.Open();  
  99.             SqlCommand cmd = new SqlCommand(cmdText, conn);  
  100.             DataSet ds = new DataSet();  
  101.             SqlDataAdapter da = new SqlDataAdapter(cmd);  
  102.             da.Fill(ds);  
  103.             dt = ds.Tables[0];  
  104.         }  
  105.         catch (SqlException se)  
  106.         {  
  107.             throw new Exception(se.Message, se);  
  108.         }  
  109.         finally  
  110.         {  
  111.             conn.Close();  
  112.         }  
  113.         return dt;  
  114.     }  
  115. }  

6. 创建数据库对象的实体类,也是十分简单的,就是对应数据库的字段;

 
  
  1. /*  
  2.  * 文件名:Message  
  3.  * 说明:Message实体类  
  4.  * 作者:Alexis  
  5.  * 网站:http://alexis.blog.51cto.com/
  6.  * 创建时间:20100428  
  7.  * */  
  8. using System;  
  9. using System.Collections.Generic;  
  10. using System.Linq;  
  11. using System.Web;  
  12.  
  13. namespace MessageBoard  
  14. {  
  15.     /// <summary> 
  16.     /// 留言类  
  17.     /// </summary> 
  18.     public class Message  
  19.     {  
  20.         private int id;//留言的标识  
  21.  
  22.         public int Id  
  23.         {  
  24.             get { return id; }  
  25.             set { id = value; }  
  26.         }  
  27.  
  28.         private string msg_content;//留言的内容  
  29.  
  30.         public string Msg_content  
  31.         {  
  32.             get { return msg_content; }  
  33.             set { msg_content = value; }  
  34.         }  
  35.  
  36.         private string msg_nickname;// 昵称  
  37.  
  38.         public string Msg_nickname  
  39.         {  
  40.             get { return msg_nickname; }  
  41.             set { msg_nickname = value; }  
  42.         }  
  43.  
  44.         private string msg_face;//选择的头像  
  45.  
  46.         public string Msg_face  
  47.         {  
  48.             get { return msg_face; }  
  49.             set { msg_face = value; }  
  50.         }  
  51.  
  52.         private DateTime msg_time;//留言的时间  
  53.  
  54.         public DateTime Msg_time  
  55.         {  
  56.             get { return msg_time; }  
  57.             set { msg_time = value; }  
  58.         }  
  59.  
  60.     }  

7.开始着手写js代码,在写ajax事件之前,先来看下两个jQuery插件,首先是jQuery文本框水印效果,效果图如下:

 使用方法:添加watermarkinput 的js引用,为想要实现水印效果的文本框加上id如,

 
  
  1. <input type="text" id="msg_nickname" size="40" /> 之后再js代码中写如下的代码以处理水印//处理水印  
  2.         jQuery(function ($) {  
  3.             $("#msg_nickname").Watermark("请输入您的昵称,如果不输入则默认为匿名");  
  4.         });  
  5.         function UseData() {  
  6.             $.Watermark.HideAll();   //Do Stuff     
  7.             $.Watermark.ShowAll();  
  8.         } 

8. jQuery图片缩放插件,jquery.imgzoom.js ,具体的效果:点击图标的时候,图片渐渐变大,直至原来的大小,如果是Gif图片的话,效果会更好。

9. 编写具体的Ajax代码,使用jQuery框架将会节省很多的时间,当我们点击留言按钮的时候,将一些信息收集起来,然后通过Ajax写入数据库,然后使用布局修改DOM来实现无刷新的效果,主要的代码如下:

 
  
  1. //使用ajax处理留言  
  2.                 $.ajax({  
  3.                     type: "POST",  
  4.                     url: "Ajax/MessageBoardHandler.ashx?action=add",  
  5.                     data: "msg_nickname=" + escape(msg_nickname) + "&msg_content=" + escape(msg_content) + "&msg_time=" + msg_time + "&msg_face=" + msg_face,  
  6.                     success: function (msg) {  
  7.                         //在table中新增一行  
  8.                         if (msg == "success") {  
  9.                             $('#messagelist').append("<div class='box clearfix' id=''><img src='" + msg_face +  
  10.                                 "' alt='' width='50' height='50' class='avatar' /><div class='text'><strong><a href='#'>" + msg_nickname + "</a></strong><p>" + msg_content +"</p><div class='date'>"+msg_time+"</div></div></div>");  
  11.                         }  
  12.                     }  
  13.                 }); 

上面的一些变量重字面上也能知道是我们收集的信息,即要写如数据库的留言信息;
 

10. 编写Ajax处理类的代码,将信息插入数据库,代码如下:

 
  
  1. public void ProcessRequest(HttpContext context)  
  2.         {  
  3.             context.Response.ContentType = "text/plain";  
  4.             string action = context.Request.Params["action"].ToString();//获取想要做的操作  
  5.  
  6.             if (action == "add")//新增留言  
  7.             {  
  8.                 Message message = new Message();//创建新的留言对象  
  9.                 message.Msg_nickname = context.Request.Params["msg_nickname"].ToString();//昵称  
  10.                 message.Msg_content = context.Request.Params["msg_content"].ToString();//留言内容  
  11.                 message.Msg_time = DateTime.Parse(context.Request.Params["msg_time"].ToString());//留言时间  
  12.                 message.Msg_face = context.Request.Params["msg_face"].ToString();//选择的头像  
  13.                 MessageAdd(message,context);  
  14.             }  
  15.             else if (action=="del")//删除留言  
  16.             {  
  17.                   
  18.             }  
  19.         }  
  20.  
  21.         /// <summary> 
  22.         /// 新增留言  
  23.         /// </summary> 
  24.         /// <param name="message"></param> 
  25.         private void MessageAdd(Message message, HttpContext context)  
  26.         {  
  27.             SQLHelper helper = new SQLHelper();  
  28.             string cmdText = "INSERT INTO TB_MESSAGE_BOARD(MSG_USER,MSG_CONTENT,MSG_FACE,MSG_TIME) VALUES('" +  
  29.                 message.Msg_nickname + "','" + message.Msg_content + "','" + message.Msg_face + "','" + message.Msg_time + "')";  
  30.             if(helper.RunSQL(cmdText, null))  
  31.             {  
  32.                 context.Response.Write("success");  
  33.             }  
  34.         } 

在这个类里面就用到了SQL Helper了;

 11. 编写MessageBoard的后台代码,我们在加载留言本页面的时候,需要将已有的留言信息显示在页面中,

 
  
  1. /*  
  2.  * 文件名:MessageBoard  
  3.  * 说明:使用Ajax的留言板  
  4.  * 作者:Alexis  
  5.  * 网站:http://alexis.blog.51cto.com/  
  6.  * 创建时间:20101226  
  7.  * */  
  8. using System;  
  9. using System.Collections.Generic;  
  10. using System.Linq;  
  11. using System.Web;  
  12. using System.Web.UI;  
  13. using System.Web.UI.WebControls;  
  14. using System.Data.SqlClient;  
  15. using System.Data;  
  16.  
  17. namespace MessageBoard  
  18. {  
  19.     public partial class MessageBoard : System.Web.UI.Page  
  20.     {  
  21.         protected DataTable dt;  
  22.  
  23.         protected void Page_Load(object sender, EventArgs e)  
  24.         {  
  25.             GetMessage();  
  26.         }  
  27.  
  28.         //从数据库中读取留言信息  
  29.         protected void GetMessage()  
  30.         {  
  31.             SQLHelper helper = new SQLHelper();  
  32.             dt=helper.getDataTable("select * from tb_message_board");  
  33.  
  34.         }  
  35.     }  

12. 在前台显示这些数据,使用的内部变量,即 <%=dt.Rows[i]["msg_time"]%>这种形式的代码,详细的代码可以参考源文件