zoukankan      html  css  js  c++  java
  • Repeater+AspNetPager+Ajax留言板

    主要结构:

      1.前期准备

      2.Repeater+AspNetPager分页效果

      3.Ajax无刷新留言板,插入和删除留言

      4.自定义编号

      5.总结

      先上效果图:(PS:美工很一般)

      


      1.前期准备:

      1.数据库:自增ID,用户名,留言内容,用户头像,留言时间。

      

      2.实体类:对应数据库的字段

    View Code
     1 public class MessageClass
    2 {
    3 private int id;
    4 public int ID //自增ID
    5 {
    6 get { return id; }
    7 set { id = value; }
    8 }
    9
    10 private string username;
    11 public string UserName //用户名
    12 {
    13 get { return username; }
    14 set { username = value; }
    15 }
    16
    17 private string usermessage;
    18 public string UserMessage //留言内容
    19 {
    20 get { return usermessage; }
    21 set { usermessage = value; }
    22 }
    23
    24 private string userimage;
    25 public string UserImage //用户头像
    26 {
    27 get { return userimage; }
    28 set { userimage = value; }
    29 }
    30
    31 private DateTime usertime;
    32 public DateTime UserTime //留言时间
    33 {
    34 get { return usertime; }
    35 set { usertime = value; }
    36 }
    37 }

      3.数据访问层:

    View Code
      1 public class SqlHelper
    2 {
    3 public readonly static string connectionString = ConfigurationManager.ConnectionStrings["connstring"].ToString();
    4
    5 public static SqlConnection conn = new SqlConnection(connectionString);
    6
    7 public static void OpenConnection()
    8 {
    9
    10 if (conn.State != ConnectionState.Open)
    11 {
    12 try
    13 {
    14 conn.Open();
    15 }
    16 catch (Exception ex)
    17 {
    18 conn.Dispose();
    19 throw new Exception("Connect Database error!" + ex.Message);
    20 }
    21 }
    22 }
    23
    24 public static void CloseConnection()
    25 {
    26 if (conn.State==ConnectionState.Open)
    27 {
    28 try
    29 {
    30 conn.Close();
    31 }
    32 catch (Exception ex)
    33 {
    34 conn.Dispose();
    35 throw new Exception("Close Database error!" + ex.Message);
    36 }
    37 }
    38 }
    39
    40 /// <summary>
    41 /// 执行带参数的SQL语句
    42 /// </summary>
    43 /// <param name="sql"></param>
    44 /// <returns></returns>
    45 public static bool ExecuteNoReturn(string sql)
    46 {
    47 try
    48 {
    49 SqlCommand comm = new SqlCommand(sql, conn);
    50 OpenConnection();
    51 comm.ExecuteNonQuery();
    52 CloseConnection();
    53 return true;
    54 }
    55 catch (Exception ex)
    56 {
    57 return false;
    58 throw new Exception("Error:" + ex);
    59 }
    60 }
    61
    62 /// <summary>
    63 /// 执行带参数的SQL语句,返回个数
    64 /// </summary>
    65 /// <param name="sql"></param>
    66 /// <returns></returns>
    67 public static int ExecuteReturnCount(string sql)
    68 {
    69 try
    70 {
    71 SqlCommand comm = new SqlCommand(sql, conn);
    72 OpenConnection();
    73 int count =(int) comm.ExecuteScalar();
    74 CloseConnection();
    75 return count;
    76 }
    77 catch (Exception ex)
    78 {
    79 return 0;
    80 throw new Exception("Error:" + ex);
    81 }
    82 }
    83
    84 /// <summary>
    85 /// 执行SQL命令,将数据赋给数据集
    86 /// </summary>
    87 /// <param name="sql"></param>
    88 /// <returns></returns>
    89 public static DataTable ExcuteSqlReturnTable(string sql)
    90 {
    91 try
    92 {
    93 OpenConnection();
    94 SqlCommand comm = new SqlCommand(sql, conn);
    95 SqlDataAdapter adpater = new SqlDataAdapter(comm);
    96 DataTable dt = new DataTable();
    97 adpater.Fill(dt);
    98 CloseConnection();
    99 return dt;
    100 }
    101 catch (Exception ex)
    102 {
    103 return null;
    104 throw new Exception("Error:" + ex);
    105 }
    106
    107 }
    108 }

      
      2.Repeater+AspNetPager分页效果

      一直都用Repeater控件,灵活性高,但是之前的分页都是自己手写的,感觉比较繁琐。于是就尝试用了AspNetPager分页控件,效果还是挺不错的。

      我将总记录数,每页显示的项数,当前页索引声明为public,是为了插入数据时,js引用,从而实现自动倒序排列的功能。

      前台代码:

    View Code
     1 <div id="msglist">
    2 <asp:Repeater ID="Rep" runat="server">
    3 <ItemTemplate>
    4 <table class="tablestyle">
    5 <tr>
    6 <td class="lf">
    7 <ul>
    8 <li><a href="#"><img src='<%#Eval("UserImage") %>' alt="0"/></a></li>
    9 <li><em><%#Eval("UserName") %></em></li>
    10 <li>(<%#Eval("UserName") %>)</li>
    11 <li>等级:★★★★★</li>
    12 <li>结贴率:100%</li>
    13 </ul>
    14 </td>
    15 <td class="rw">
    16 <div class="fbart">发表于:<%#Eval("UserTime", "{0:yyyy-M-dd HH:mm:ss}")%><em><%#RowsCount - (PageNum-1) *PageSize- Container.ItemIndex%></em></div>
    17 <div class="msgfont"><%#Eval("UserMessage") %></div>
    18 <div class="fdart"><span class='<%#Eval("ID") %>'><a href="" class="btndelete" onclick="return false">删除</a></span></div>
    19 </td>
    20 </tr>
    21 </table>
    22 </ItemTemplate>
    23 </asp:Repeater>
    24 </div>
    25 <div id="page">
    26 <webdiyer:AspNetPager ID="AspNetPager1" OnPageChanged="AspNetPager1_PageChanged" CssClass="paginator" CurrentPageButtonPosition="Center" PageIndexBoxType="DropDownList" ShowPageIndexBox="Always" SubmitButtonText="Go" TextAfterPageIndexBox="页" TextBeforePageIndexBox="转到" runat="server" >
    27 </webdiyer:AspNetPager>
    28 </div>



      后台代码:

    View Code
     1 protected void Page_Load(object sender, EventArgs e)
    2 {
    3 if (!IsPostBack)
    4 {
    5 AspNetPagerConfig();
    6 MessageList();
    7 }
    8 }
    9 //总记录数
    10 private int rowscount= 0;
    11 protected int RowsCount
    12 {
    13 get{ return rowscount;}
    14 set{this.rowscount = value;}
    15 }
    16 //每页显示的项数
    17 private int pagesize = 0;
    18 protected int PageSize
    19 {
    20 get { return pagesize; }
    21 set {this.pagesize=value; }
    22 }
    23 //当前索引
    24 private int pagenum = 0;
    25 protected int PageNum
    26 {
    27 get { return pagenum; }
    28 set { this.pagenum = value; }
    29 }
    30 //AspNetPager配置
    31 protected void AspNetPagerConfig()
    32 {
    33 string sql = "select count(*) from T_BBS";
    34 int count = SqlHelper.ExecuteReturnCount(sql);
    35 AspNetPager1.RecordCount = count;//设置总页数
    36 RowsCount = count;
    37 AspNetPager1.PageSize = 2;
    38 AspNetPager1.PrevPageText = "上一页";
    39 AspNetPager1.NextPageText = "下一页";
    40 AspNetPager1.FirstPageText = "首页";
    41 AspNetPager1.LastPageText = "尾页";
    42 AspNetPager1.ShowFirstLast = false;
    43 AspNetPager1.ShowMoreButtons = false;
    44 }
    45
    46 //绑定Repeater数据源
    47 protected void MessageList()
    48 {
    49 pagesize = AspNetPager1.PageSize;//得到每页显示的项数
    50 pagenum = AspNetPager1.CurrentPageIndex;//得到当前页索引
    51 int count2 = (pagenum - 1) * pagesize;
    52 string sql = "select top " + pagesize + " * from T_BBS where id not in(select top " + count2 + " id from T_BBS order by usertime desc) order by usertime desc ";
    53 DataTable dt = SqlHelper.ExcuteSqlReturnTable(sql);
    54 Rep.DataSource = dt;
    55 Rep.DataBind();
    56 }
    57
    58 // AspNetPager控件改变页事件
    59 protected void AspNetPager1_PageChanged(object src, EventArgs e)
    60 {
    61 AspNetPagerConfig();
    62 MessageList();
    63 }


      3.Ajax无刷新留言板,增加删除留言

      主要通过一般处理程序ashx处理提交的数据,再根据自己的需求返回数据

      删除留言可以有两个方法:1.根据查找返回的id,这个正是本文所提到的。 2.根据查找用户留言的时间,之后完善会做到这个方面。

      js代码:

    View Code
     1  //插入留言
    2 $("#btnInsert").click(function () {
    3 if ($("#txtname").val() == "若不填则为匿名") {
    4 var username = "匿名";
    5 }
    6 else {
    7 var username = $("#txtname").val(); //用户名
    8 }
    9 var usermessage = $("#txtmessage").val(); //留言内容
    10 var Time = new Date();
    11 var usertime = Time.getFullYear() + "-" + (Time.getMonth() + 1) + "-" + Time.getDate() + " " + Time.getHours() + ":" + Time.getMinutes() + ":" + Time.getSeconds(); //获取留言的时间
    12 var RowsCount = "<%=RowsCount %>";
    13 var PageSize = "<%=PageSize %>";
    14 var PageNum = "<%=PageNum %>";
    15 $.ajax({
    16 type: "POST",
    17 url: "Handler/Message.ashx?method=add",
    18 data: "username=" + username + "&usermessage=" + usermessage + "&userimage=" + userimage + "&usertime=" + usertime + "",
    19 success: function (data) {
    20 if (data != "-1") {
    21 num++;
    22 $("#msglist").prepend("<table class='tablestyle'><tr><td class='lf'><ul><li><a href='#'><img src='" + userimage + "'alt='0'/></a></li><li><em>" + username + "</em></li><li>(" + username + ")</li><li>等级:★★★★★</li><li>结贴率:100%</li></ul></td><td class='rw'><div class='fbart'>发表于:" + usertime + "<em>" + (RowsCount - (PageNum - 1) * PageSize + num) + "</em></div><div class='msgfont'>" + usermessage + "</div><div class='fdart'><span class=" + data + "><a href='' class='btndelete' onclick='return false'>删除</a></span></div></td></tr></table>");
    23 $(".btndelete").bind("click", deleteEvent); //重新绑定删除按钮事件
    24 }
    25 }
    26 });
    27 });
    28 //删除留言
    29 $(".btndelete").click("click", deleteEvent);
    30 var deleteEvent = function () {
    31 if (!confirm("是否确定要删除这条留言"))
    32 return false;
    33 var deletelist = $(this).parent(); //获取父标签
    34 var deletepar = $(this).parents(".tablestyle"); //获取当前tablestyle
    35 var id = deletelist.attr("class"); //获取要删除行的id值
    36 $.ajax({
    37 type: "POST",
    38 url: "Handler/Message.ashx?method=delete",
    39 data: "id=" + id + "",
    40 success: function (data) {
    41 if (data == "success") {
    42 deletepar.animate({ opacity: 'hide' }, "slow", function () { deletepar.remove(); });
    43 }
    44 }
    45 });
    46 }

      一般处理程序代码:

    View Code
     1 public void ProcessRequest (HttpContext context) {
    2 context.Response.ContentType = "text/plain";
    3 string method = context.Request.Params["method"].ToString();//获取想要做的操作
    4 if (method == "add")
    5 {
    6 MessageClass message = new MessageClass();//创建新的留言对象
    7 message.UserName = context.Request.Params["username"].ToString();
    8 message.UserMessage = context.Request.Params["usermessage"].ToString();
    9 message.UserImage = context.Request.Params["userimage"].ToString();
    10 message.UserTime = Convert.ToDateTime(context.Request.Params["usertime"].ToString());
    11 InsertMessage(message, context);
    12 }
    13 if (method == "delete")
    14 {
    15 int id = Convert.ToInt32(context.Request.Form["id"].ToString());
    16 DeleteMessage(id, context);
    17 }
    18 }
    19 /// <summary>
    20 /// 插入留言
    21 /// </summary>
    22 /// <param name="message">传递的对象</param>
    23 /// <param name="context"></param>
    24 public void InsertMessage(MessageClass message, HttpContext context)
    25 {
    26 string sql = "insert into T_BBS (username,usermessage,userimage,usertime) values ('" + message.UserName + "','" + message.UserMessage + "','" + message.UserImage + "','" + message.UserTime + "')";
    27 bool flag= SqlHelper.ExecuteNoReturn(sql);
    28 if (flag)
    29 {
    30 string sqlstring = "select top 1 id from T_BBS order by usertime desc";
    31 DataTable dt = SqlHelper.ExcuteSqlReturnTable(sqlstring);
    32 context.Response.Write(dt.Rows[0][0].ToString());
    33 }
    34 else
    35 {
    36 context.Response.Write("-1");
    37 }
    38 }
    39 /// <summary>
    40 /// 删除留言
    41 /// </summary>
    42 /// <param name="id">特定的id值</param>
    43 /// <param name="context"></param>
    44 public void DeleteMessage(int id, HttpContext context)
    45 {
    46 string sql = "delete from T_BBS where id="+id+"";
    47 bool flag = SqlHelper.ExecuteNoReturn(sql);
    48 if (flag)
    49 {
    50 context.Response.Write("success");
    51 }
    52 else
    53 {
    54 context.Response.Write("error");
    55 }
    56 }

      4.自定义编号

      主要思想是绑定AspNetPager的总记录数,每页显示的项数,当前页索引进行一些简单运算即可。

      而对新插入的留言进行编号,大体是一样的,就是多给了一个值num,每次插入都num++

      代码:

    <%#RowsCount - (PageNum-1) *PageSize- Container.ItemIndex%>

     

  • 相关阅读:
    Open diary(每天更新)
    独立博客与秘密基地,以及对UI设计中拟物态的怀念
    如何在宝塔面板里设置脚本定时恢复数据库
    LaTex公式语法教程及手册(附emlogpro公式显示插件katex说明)
    关于梦的冷知识
    PTui又加全景图 佳田未来城 of 安阳
    原生js 以ajax(post)的方式传json至php,并让php解析为数组
    Python面向对象——
    Python中的模块、常用模块——12
    Python中的装饰器——11
  • 原文地址:https://www.cnblogs.com/Kung/p/messageboard.html
Copyright © 2011-2022 走看看