zoukankan      html  css  js  c++  java
  • AJAX简单的数据增删改与分页应用

    运行截图:

    PageBar.js:

      1 /*
      2  *  说明:
      3  *      整体思想,1.第一页时不显示:首页,上一页,
      4  *               2.最后一页时不显示:下一页,尾页
      5  *               3.中间有 5 页导航,
      6  *                  若:3.1.(总页数<5),就显示多少,
      7  *                      3.2.(总页数>5),点击页码值 <=3 背景为灰色还在那个位置,
      8  *                                   点击页码值 >3 背景为灰色的始终在中间,
      9  *                                   点击页码值 为最后三个,背景为灰色的还在那个位置
     10  *               4.后面追加一个跳转项
     11  *               5.显示不显示一共多少页,纠结中......
     12  */
     13 //添加实用集
     14 /// <reference path="Utility.js" />
     15 
     16 //总页数:要求对象请求一次更新一次
     17 var pageCount = false;
     18 ////请求页面值
     19 //var pageIndex = false;
     20 //页码阵列点击函数名
     21 var FUN = false;
     22 //表名称标识
     23 var TBLNAME = false;
     24 
     25 //页码条容器
     26 function pageNavigatorPanel() {
     27     var pnp = GetObject(arguments[0]);
     28     //预留样式:
     29     return pnp;
     30 };
     31 
     32 //创建跳转标签
     33 function PageGoto() {
     34     return PageTemplate("跳转", "page", "pGoto", arguments);
     35 };
     36 
     37 //创建尾页标签
     38 function PageTrailer() {
     39     return PageTemplate("尾页", "page", "pTrailer", arguments);
     40 };
     41 
     42 //创建下一页标签
     43 function PageNext() {
     44     return PageTemplate("下一页", "page", "pNext", arguments);
     45 };
     46 
     47 //创建上一页标签
     48 function PagePrevious() {
     49     return PageTemplate("上一页", "page", "pPrevious", arguments);
     50 };
     51 
     52 //创建首页标签
     53 function PageFirst() {
     54     return PageTemplate("首页", "page", "pFirst", arguments);
     55 };
     56 
     57 //创建页码阵列 元素id="Nav"+tit 某阵列中的元素被点击之后为其 class 添加 pageB 样式
     58 function PageNavigatorItem(tit) {
     59     return PageTemplate(tit, "page", "Nav" + TBLNAME + tit, arguments);
     60 };
     61 
     62 //创建标签母版 如需要style在外部重新定义
     63 function PageTemplate(tit, cla, idn, args) {
     64     var pTemplate = document.createElement("a");
     65     pTemplate.title = tit;
     66     pTemplate.className = cla;
     67     pTemplate.id = idn;
     68     //pTemplate.style = sty;
     69     pTemplate.innerHTML = tit;
     70     //根据  Request("get", "SList.ashx?pi=" + arguments[0] + "&name=" + arguments[1], 。。。。请求条件只要两个参数即可。
     71     var hrf = "javascript:" + FUN + "(";
     72     var arg3 = arguments[3];
     73     if (arg3 != null) {// && arg3.length > 1) {
     74         for (var i = 0; i < 1; i++) {
     75             hrf += arg3[i] + ","";
     76         }
     77         //hrf = hrf.substr(0, hrf.length - 1);
     78         hrf += TBLNAME + """;
     79     }
     80     hrf += ");";
     81     pTemplate.href = hrf;
     82     return pTemplate;
     83 };
     84 //清空PageBar
     85 function EmptyPageBar() {
     86     GetObject(arguments[0]).innerHTML ="";
     87 };
     88 //根据请求页码显示分页条. 
     89 function Paging(panelId, pageindex, funNavigateOnClickName, tblName) {
     90     EmptyPageBar(panelId);
     91     FUN = funNavigateOnClickName;
     92     TBLNAME = tblName;
     93     var pnp = pageNavigatorPanel(panelId);
     94     if (pageCount == 0) {//不足一页:显示第一页
     95         pnp.appendChild(PageNavigatorItem(1, 1));
     96     }
     97     else {
     98         //1.首页显示条件
     99         if (pageCount > 5 && pageindex > 3) {//若第一页不再阵列中就显示:
    100             pnp.appendChild(PageFirst(1));//首页
    101         }
    102         //2.上一页显示条件
    103         if (pageindex != 1) {//若不是第一页就显示:  
    104             pnp.appendChild(PagePrevious(pageindex - 1));//上一页
    105         }
    106         //3.页码条阵列显示
    107         if (pageCount < 6) {//5页之内:样式点击那个哪个背景为灰色。
    108             for (var i = 1; i <= pageCount; i++) {//添加和pageCount相等的页码条阵列
    109                 pnp.appendChild(PageNavigatorItem(i, pageindex));
    110             }
    111         } else {//大于5页(2 < pageindex < pageCount-1)的样式:灰色背景
    112             //3.1前三个跟着走
    113             if (pageindex <= 3) {
    114                 for (var i = 1; i < 6; i++) {
    115                     pnp.appendChild(PageNavigatorItem(i, pageindex));
    116                 }
    117             }
    118             //3.2一直在中间
    119             if (3 < pageindex && pageindex < pageCount - 2) {
    120                 for (var i = pageindex - 2; i < pageindex + 3; i++) {
    121                     pnp.appendChild(PageNavigatorItem(i, pageindex));
    122                 }
    123             }
    124             //3.3后三个跟着走
    125             if (pageindex >= pageCount - 2) {
    126                 for (var i = pageCount - 4; i <= pageCount; i++) {
    127                     pnp.appendChild(PageNavigatorItem(i, pageindex));
    128                 }
    129             }
    130         }
    131         //4.下一页显示条件
    132         if (pageindex < pageCount) {//若不是最后一页就显示:
    133             pnp.appendChild(PageNext(pageindex + 1));//下一页
    134         }
    135         //5.尾页显示条件(若最后一页不再阵列中)
    136         if (pageindex < pageCount - 2) {
    137             pnp.appendChild(PageTrailer(pageCount));//尾页
    138         }
    139         //为点击元素附加类样式pageB,并且禁用a标签。
    140         var aTag = GetObject("Nav" + TBLNAME + pageindex);
    141         aTag.className += " pageB";
    142          aTag.removeAttribute("href");
    143         //下面这个无效
    144         //aTag.onclick = function () { return false; };
    145         //增加跳转条件
    146         if (pageCount > 18) {//页数大于18 才有显示的必要
    147             //跳转输入框变量
    148             var gt = '&nbsp;&nbsp;至第<input type="text" id="pGoto" style="border:1px solid rgb(206,206,206); 31px;height:19px;margin:1px 0;text-align:center;" />页&nbsp;';
    149             pnp.innerHTML += gt;
    150             pnp.appendChild(PageGoto(parseInt(GetObject("pGoto").value)));//NaN
    151         }
    152     }
    153 };
    View Code

    修改后更通用的

    PageBar.js

    /*  Author:
     *      By Wang
     *
     *  说明:
     *      整体思想,1.第一页时不显示:首页,上一页,
     *               2.最后一页时不显示:下一页,尾页
     *               3.中间有 5 页导航,
     *                  若:3.1.(总页数<5),就显示多少,
     *                      3.2.(总页数>5),点击页码值 <=3 背景为灰色还在那个位置,
     *                                   点击页码值 >3 背景为灰色的始终在中间,
     *                                   点击页码值 为最后三个,背景为灰色的还在那个位置
     *               4.后面追加一个跳转项
     *               5.显示不显示一共多少页,纠结中......
     *      主函数:Paging
     */
    //添加实用集
    /// <reference path="Utility.js" />
    
    //总页数:要求对象请求一次更新一次
    //var pageCount = false;
    ////请求页面值
    //var pageIndex = false;
    //页码阵列点击函数名
    var FUN = false;
    var IDPR = "Page";
    //页码条容器
    function pageNavigatorPanel() {
        var pnp = GetObject(arguments[0]);
        //预留样式:
        return pnp;
    };
    
    //创建跳转标签
    function PageGoto() {
        return PageTemplate("跳转", "page", IDPR + "Goto", arguments);
    };
    
    //创建尾页标签
    function PageTrailer() {
        return PageTemplate("尾页", "page", IDPR + "Trailer", arguments);
    };
    
    //创建下一页标签
    function PageNext() {
        return PageTemplate("下一页", "page", IDPR + "Next", arguments);
    };
    
    //创建上一页标签
    function PagePrevious() {
        return PageTemplate("上一页", "page", IDPR + "Previous", arguments);
    };
    
    //创建首页标签
    function PageFirst() {
        return PageTemplate("首页", "page", IDPR + "First", arguments);
    };
    
    //创建页码阵列 元素id="Nav"+tit 某阵列中的元素被点击之后为其 class 添加 pageB 样式
    function PageNavigatorItem(tit) {
        return PageTemplate(tit, "page", IDPR + tit, arguments);//默认有一个page样式
    };
    
    //创建标签母版: tit:显示内容,cla:样式类名,idn:id名称,args:参数
    function PageTemplate(tit, cla, idn, args) {
        var pTemplate = document.createElement("a");
        pTemplate.title = tit;
        pTemplate.className = cla;
        pTemplate.id = idn;
        //pTemplate.style = sty;
        pTemplate.innerHTML = tit;
        //点击执行的js函数
        var hrf = "javascript:" + FUN + "(";
        var arg3 = arguments[3];
        //if (arg3 != null && arg3.length > 1) {
        //for (var i = 0; i < 1; i++) {
        hrf += ("'" + idn + "',");
        hrf += arg3[0];
        //}
        //}
        hrf += ");";
        pTemplate.href = hrf;
        return pTemplate;
    };
    //清空PageBar
    function EmptyPageBar() {
        GetObject(arguments[0]).innerHTML = "";
    };
    //根据请求页码显示分页条. 
    function Paging(panelId, pageindex, pageCount, pageTagClickFuncName) {
        EmptyPageBar(panelId);
        FUN = pageTagClickFuncName;
        var pnp = pageNavigatorPanel(panelId);
        if (pageindex == 0) {
            pnp.innerHTML = "<strong color='red'>对不起,没有数据...</strong>";
            return;
        }
        if (pageCount == 0) {//不足一页:显示第一页
            pnp.appendChild(PageNavigatorItem(1));
        }
        else {
            //1.首页显示条件
            if (pageCount > 5 && pageindex > 3) {//若第一页不再阵列中就显示:
                pnp.appendChild(PageFirst(1));//首页
            }
            //2.上一页显示条件
            if (pageindex != 1) {//若不是第一页就显示:  
                pnp.appendChild(PagePrevious(pageindex - 1));//上一页
            }
            //3.页码条阵列显示
            if (pageCount < 6) {//5页之内:样式点击那个哪个背景为灰色。
                for (var i = 1; i <= pageCount; i++) {//添加和pageCount相等的页码条阵列
                    pnp.appendChild(PageNavigatorItem(i));
                }
            } else {//大于5页(2 < pageindex < pageCount-1)的样式:灰色背景
                //3.1前三个跟着走
                if (pageindex <= 3) {
                    for (var i = 1; i < 6; i++) {
                        pnp.appendChild(PageNavigatorItem(i));
                    }
                }
                //3.2一直在中间
                if (3 < pageindex && pageindex < pageCount - 2) {
                    for (var i = pageindex - 2; i < pageindex + 3; i++) {
                        pnp.appendChild(PageNavigatorItem(i));
                    }
                }
                //3.3后三个跟着走
                if (pageindex >= pageCount - 2) {
                    for (var i = pageCount - 4; i <= pageCount; i++) {
                        pnp.appendChild(PageNavigatorItem(i));
                    }
                }
            }
            //4.下一页显示条件
            if (pageindex < pageCount) {//若不是最后一页就显示:
                pnp.appendChild(PageNext(pageindex + 1));//下一页
            }
            //5.尾页显示条件(若最后一页不再阵列中)
            if (pageindex < pageCount - 2) {
                pnp.appendChild(PageTrailer(pageCount));//尾页
            }
            //增加跳转条件
            if (pageCount > 10) {//页数大于10 才有显示的必要
                //跳转输入框变量
                var gt = '&nbsp;&nbsp;至第<input type="text" id="PageGotoIndex" style="border:1px solid rgb(206,206,206); 31px;height:19px;margin:1px 0;text-align:center;" />页&nbsp;';
                pnp.innerHTML += gt;
                pnp.appendChild(PageGoto(parseInt(GetObject("PageGotoIndex").value)));//NaN
            }
        }
        //为点击元素附加类样式pageB,并且禁用a标签。
        var aTag = GetObject(IDPR + pageindex);
        if (typeof (aTag) != "undefined") {
            aTag.className += " pageB";
            aTag.removeAttribute("href");
        }
        //下面这个无效
        //aTag.onclick = function () { return false; };
    };

    Utility.js

     1 /*
     2  * js实用工具箱
     3  */
     4 
     5 //根据id获取对象:传递一个参数id
     6 function GetObject() {
     7     return document.getElementById(arguments[0]);
     8 };
     9 
    10 //创建对象
    11 function SetObject() {
    12     return document.createElement(arguments[0]);
    13 };
    14 
    15 //根据id获取对象:指示在浏览器中是否隐藏{false:"block",ture:"none"}
    16 function Display(id, bool) {
    17     var dis = "block";
    18     if (bool)
    19         dis = "none";
    20     GetObject(id).style.display = dis;
    21 };
    22 
    23 //将从集合中转换出来的Json类型时间格式(/Date(308592000000)/)转换成正常格式spli="-"(year-month-day)
    24 function GetDateFromJsonDate(jsonDate, spli) {
    25     if (spli == null || spli == undefined)
    26         //spli = "/";//数据插入失败
    27     spli = "-";
    28     //   \/Date(308592000000)\/
    29     //    /Date(308592000000)/
    30     var fakeDate = arguments[0];
    31     //1.取数字转换为十进制整数
    32     fakeDate = fakeDate.match(/d+/);//1.推荐.保险
    33     //fakeDate = fakeDate.replace("/", "").replace("Date(", "").replace(")", "").replace("/", "");//2.
    34     //fakeDate = fakeDate.substring(6, fakeDate.length - 2);
    35     //2.解析为十进制数字
    36     var dec = parseInt(fakeDate, 10);
    37     //3.获取date对象
    38     var date = new Date(dec)
    39     //4.拼接格式化
    40     var day = date.getDate();
    41     var mon = date.getMonth() + 1;
    42     return date.getFullYear() + spli + (mon < 10 ? "0" + mon : mon) + spli + (day < 10 ? "0" + day : day);
    43 };
    44 
    45 //获取AJAX中的异步对象
    46 function GetXHR() {
    47     var XHR = false;
    48     /* try {
    49          XHR = new ActiveXObject("Msxml2.XMLHTTP"); // ie msxml3.0+
    50      } catch (M2) {
    51          try {
    52              XHR = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml2.6
    53          } catch (Mt) {
    54              XHR = false;
    55          }
    56      }
    57      if (!XHR && typeof XMLHttpRequest != 'undefined') {// Firefox, Opera 8.0+, Safari
    58          XHR = new XMLHttpRequest();
    59      }*/
    60     XHR = new XMLHttpRequest();
    61     return XHR;
    62 };
    63 
    64 //实现异步对象的Request请求
    65 function Request(method, url, iscache, funNameDoResponse, funNameDoErrorBystatus, send) {
    66     var xhr = GetXHR();
    67     xhr.open(method, url, true);
    68     if (method.toLowerCase() == "post")     //application/x-www-form-urlencoded
    69         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    70     if (iscache)
    71         xhr.setRequestHeader("If-Modified-Since", "0");
    72     xhr.onreadystatechange = function () {
    73         if (xhr.readyState == 4) {
    74             if (xhr.status == 200) {
    75                 //如果是值是空 json数组是null ,而不是 ""=""
    76                 var cont = xhr.responseText;//{"Id":1,"Math":null,"English":40}
    77                 //将json 字符串传入-->
    78                 funNameDoResponse(cont);
    79             } else {
    80                 if (funNameDoErrorBystatus != null)
    81                     funNameDoErrorBystatus(xhr.status);
    82             }
    83         }
    84     };
    85     xhr.send(send);
    86 };
    View Code

    PageBarStyle.css

     1 .page {
     2     background-color: rgba(255, 255, 255, 1.00);
     3     text-decoration: none; /*去掉下滑线*/
     4     color: rgb(102,102,102);
     5     /*align-content: center;*/
     6     font-size: 12px;
     7     font-family: 'MS PMincho';
     8     border: 1px solid rgb(206,206,206);
     9     padding: 5px 8px;
    10     margin: 1px;
    11 }
    12 
    13 a.page:hover {
    14     cursor: pointer;
    15     color: rgb(0,165,97);
    16 }
    17 /**/
    18 /* a[class*="pageB"]:visited {
    19     }*/
    20 
    21 /*MS PMincho*/
    22 .pageB {
    23     /*padding: 5px 8px; 重写要>=起效*/
    24     cursor: text;
    25     font-weight:bolder;
    26     background-color: rgb(206,206,206);
    27     color: rgb(255,255,255);
    28 }
    View Code

    List.html

      1 <!DOCTYPE html>
      2 <html xmlns="http://www.w3.org/1999/xhtml">
      3 <head>
      4     <title>学生信息列表</title>
      5     <link href="CSS/PageBarStyle.css" rel="stylesheet" />
      6     <style>
      7         .center {
      8             position: relative;
      9             left: 50%;
     10             top: 50%;
     11         }
     12 
     13         table {
     14             margin: 20px;
     15         }
     16 
     17         td {
     18             text-align: center;
     19             padding: 6px;
     20             margin: 5px;
     21             border: 1px solid #f00;
     22         }
     23 
     24         p {
     25             font-size: xx-large;
     26             color: #0026ff;
     27             padding: 5px;
     28             text-align: center;
     29         }
     30 
     31         .Add {
     32             display: none;
     33             position: fixed;
     34             left: 50%;
     35             top: 50%;
     36             border: 1px solid #b200ff;
     37             padding: 10px 0 0 10px;
     38             background-color: #ff006e;
     39             z-index: 110;
     40             opacity: 0.8;
     41             font-weight: 800;
     42         }
     43 
     44         .button {
     45             margin: 8px 10px 0 auto;
     46             padding: 5px;
     47             float: right;
     48         }
     49 
     50         input[type=button] {
     51             margin-left: 15px;
     52         }
     53 
     54         input[type=text] {
     55             margin: 2px;
     56         }
     57     </style>
     58     <script src="JS/Utility.js"></script>
     59     <script src="JS/PageBar.js"></script>
     60     <script type="text/javascript">
     61         var tblRowId = false;
     62         var tblScore = false;
     63         var tblStudent = false;
     64         var Modify = false;
     65         //辅助
     66         function Error() {
     67             alert("未知原因,操作失败");
     68             Display("scoAdd", true);
     69             Display("stuAdd", true);//
     70         };
     71         function CheckInput() {
     72             //数据库表示可以为空返回 true
     73             //if (txtName.value == "") {
     74             //    alert("请输入姓名");
     75             //    return false;
     76             //}
     77             //else if (txtAge.value == "") {
     78             //    alert("请输入年龄");
     79             //    return false;
     80             //}
     81             //else if (txtGender.value == "") {
     82             //    alert("请输入性别");
     83             //    return false;
     84             //}
     85             //else if (txtCID.value == "") {
     86             //    alert("请输入班级ID");
     87             //    return false;
     88             //}
     89             //else if (txtBirthday.value == "") {
     90             //    alert("请输入日期");
     91             //    return false;
     92             //}
     93             return true;
     94         };
     95         function Cancel() {
     96             Modify = false;//1.
     97             Display(arguments[0], true);
     98         };
     99         //End辅助
    100         //删除操作
    101         function DeleteCascade() {
    102             //遍历比较id值
    103             //var tbl = GetObject("tblSco");
    104             var length = tblScore.rows.length;
    105             for (var i = 0; i < length; i++) {
    106                 var ro = tblScore.rows.item(i)
    107                 if (ro.childNodes[0].innerHTML == tblRowId) {
    108                     // if (ro.id == "sco" + tblRowId) {
    109                     tblScore.deleteRow(i);
    110                     tblRowId = false;
    111                     return;
    112                 }
    113             }
    114             tblRowId = false;
    115         };
    116         function DeleteResult() {//实际情况下删除后要更新pageCount的,不然删除后,再跳转最后一页,什么都没有了,或出现错误。
    117             if (arguments[0] == 1) {
    118                 alert("删除成功");
    119                 //界面删除stu
    120                 //var roi = GetObject("stu" + tblRowId).getAttribute("name");
    121                 //GetObject("tblStu").deleteRow(roi);
    122                 //这样删除是错误的,表的行是动态变化的,
    123                 //GetObject("tblStu").deleteRow(tblStuRowIndex);//行索引是从 0 开始的
    124                 //var tbl = GetObject("tblStu");
    125                 length = tblStudent.rows.length;
    126                 for (var i = 0; i < length; i++) {
    127                     if (tblStudent.rows.item(i).childNodes[0].innerHTML == tblRowId) {
    128                         tblStudent.deleteRow(i);
    129                         break;
    130                     }
    131                 }
    132                 DeleteCascade();
    133                 return;
    134             }
    135             alert("删除失败");
    136         };
    137         function Delete() {
    138             if (confirm("确定要删除吗?")) {
    139                 tblRowId = arguments[0];
    140                 var send = "id=" + tblRowId;
    141                 Request("POST", "NonQuery.ashx", false, DeleteResult, null, send);
    142                 //  Request("get", "NonQuery.ashx?" + send, false, DeleteResult, null, null);
    143             }
    144         };
    145         //End删除操作
    146         //添加
    147         function AddScoResult() {
    148             Display("scoAdd", true);//无论结果如何都关闭成绩弹出框
    149             if (arguments[0] == 1) {
    150                 alert("添加成功");
    151                 return;
    152             }
    153             Error();
    154         };
    155         function AddStuResult() {
    156             Display("stuAdd", true);//结果回来然后关闭弹出框
    157             var cont = arguments[0];
    158             if (cont >= 1) {//学生插入成功:返回@@identity :自增id identity(1,1)
    159                 InitScoAdd();
    160                 //成绩没有Check:一定会在数据库添加。
    161                 Display("scoAdd", false);
    162                 txtId.value = parseInt(cont);
    163                 //这里通过对比表格的 行数据的ID值 。。。。。更新UI 
    164                 // OK(2);
    165                 return;
    166             }
    167             Error();
    168         };
    169         var txtName, txtAge, txtGender, txtCID, txtBirthday;
    170         function InitStuAdd() {
    171             //若输入框已经实例化了,修改后会自动有值
    172             if (txtName == undefined || txtName == false) {
    173                 txtName = GetObject("txtName");
    174                 txtAge = GetObject("txtAge");
    175                 txtGender = GetObject("txtGender");
    176                 txtCID = GetObject("txtCID");
    177                 txtBirthday = GetObject("txtBirthday");
    178             }
    179         };
    180         var txtId, txtMath, txtEnglish;
    181         function InitScoAdd() {
    182             if (txtId == undefined || txtId == false) {
    183                 txtId = GetObject("txtId");
    184                 txtMath = GetObject("txtMath");
    185                 txtEnglish = GetObject("txtEnglish");
    186             }
    187         };
    188         function Add() {
    189             //增加stu成功后才显示增加sco否则不显示。
    190             Display("stuAdd", false);
    191             //初始化输入框对象
    192             InitStuAdd();
    193             // OK(1);
    194         };
    195         //End添加
    196         //修改
    197         function AppendConcelButton() {
    198             var btnCnl = document.createElement("input");
    199             btnCnl.type = "button";
    200             btnCnl.onclick = function () {
    201                 Cancel("scoAdd");//点击取消按钮,
    202             };
    203             btnCnl.value = "取消";
    204             return btnCnl;
    205         };
    206         function RefreshStuUI() {
    207             var row = GetObject(tblRowId);//存在视觉性 Bug !!!
    208             //row.firstElementChild.innerHTML = txtId.value;
    209             row.children.item(1).innerHTML = txtName.value;
    210             row.childNodes[2].innerHTML = txtAge.value;
    211             row.childNodes[3].innerHTML = txtGender.value;
    212             row.children.item(4).innerHTML = txtCID.value;
    213             row.childNodes[5].innerHTML = txtBirthday.value;
    214             tblRowId = false;
    215         };
    216         function ModifyStuResult() {
    217             if (arguments[0] == 1) {
    218                 alert("修改成功");
    219                 RefreshStuUI();
    220             } else {
    221                 alert("修改失败");
    222             }
    223             Cancel("stuAdd");//无论成功失败都关闭。
    224         };
    225         function RefreshScoUI() {
    226             var row = GetObject(tblRowId);//存在视觉性 Bug !!!
    227             row.childNodes[1].innerHTML = txtMath.value;
    228             row.childNodes[2].innerHTML = txtEnglish.value;
    229             tblRowId = false;
    230         };
    231         function ModifyScoResult() {
    232             if (arguments[0] == 1) {
    233                 alert("修改成功");
    234                 RefreshScoUI();
    235             } else {
    236                 alert("修改失败");
    237             }
    238             Cancel("scoAdd");//无论成功失败都关闭。
    239         };
    240         function InitScoModify() {
    241             InitScoAdd();
    242             //给单元格赋值
    243             var row = GetObject(tblRowId);
    244             txtId.value = row.firstChild.innerHTML;
    245             // txtId.value = row.firstElementChild.innerHTML;
    246             txtMath.value = row.children.item(1).innerHTML;
    247             txtEnglish.value = row.childNodes[2].innerHTML;
    248             var ADiv = GetObject("Action");
    249             if (ADiv.childElementCount == 1)
    250                 // ADiv.insertBefore(AppendConcelButton());
    251                 ADiv.appendChild(AppendConcelButton());
    252         };
    253         function InitStuModify() {
    254             InitStuAdd();
    255             var row = GetObject(tblRowId);
    256             //txtId.value = row.firstElementChild.innerHTML;
    257             txtName.value = row.children.item(1).innerHTML;
    258             txtAge.value = row.childNodes[2].innerHTML;
    259             txtGender.value = row.childNodes[3].innerHTML;
    260             txtCID.value = row.children.item(4).innerHTML;
    261             txtBirthday.value = row.childNodes[5].innerHTML;
    262         }
    263         function Modified() {//传递ID
    264             tblRowId = arguments[0] + arguments[1];
    265             if (arguments[0] == "sco") {
    266                 Display("scoAdd", false);
    267                 Modify = true;//开启修改模式,然后,两种情况下关闭:1.点击取消。2.xhr.send()之后。
    268                 InitScoModify();
    269             } else {
    270                 //stu
    271                 Display("stuAdd", false);
    272                 Modify = true;
    273                 InitStuModify();
    274             }
    275         };
    276         //End修改
    277         //确定
    278         function OK() {
    279             if (arguments[0] == 1) {//stu
    280                 if (CheckInput()) {//发送数据
    281                     var send = "name=" + txtName.value + "&age=" + txtAge.value + "&gender=" + txtGender.value + "&cid=" + txtCID.value + "&birthday=" + txtBirthday.value;
    282                     if (!Modify)
    283                         Request("POST", "NonQuery.ashx", false, AddStuResult, Error, send);
    284                     else
    285                         Request("POST", "NonQuery.ashx?actionId=" + tblRowId.toString().substr(3), false, ModifyStuResult, Error, send);
    286                 }
    287             } else {//sco
    288                 var send = "sid=" + txtId.value + "&math=" + txtMath.value + "&english=" + txtEnglish.value;
    289                 if (!Modify)
    290                     Request("POST", "NonQuery.ashx", false, AddScoResult, Error, send);
    291                 else
    292                     Request("POST", "NonQuery.ashx?actionId=" + tblRowId.toString().substr(3), false, ModifyScoResult, Error, send);//
    293             }//看看是否进入下一步。:可以,
    294             Modify = false;//2.
    295         };
    296         function RemoveRowToTable() {
    297             var tbl = arguments[0];
    298             var i = tbl.rows.length - 2;//为不足8行除错
    299             if (tbl.rows.length > 3)
    300                 for (; i > 1; i--) {//5行数据 倒着删
    301                     tbl.deleteRow(i);
    302                 }
    303         };
    304         function InsertRowTotblSco() {
    305             var tblScoreRow = tblScore.insertRow(arguments[0]);
    306             //tblScoreRow.setAttribute("name", arguments[0]);
    307             //为了对ID进行区别
    308             tblScoreRow.id = "sco" + arguments[1]; //设置当前行的id值
    309             //
    310             var td0 = tblScoreRow.insertCell(-1);//这个没有提示~~(但是有这个方法)
    311             td0.innerHTML = arguments[1];
    312             ////火狐下不兼容
    313             //var td1 = tblScoreRow.insertBefore(document.createElement("td"));
    314             var td1 = tblScoreRow.insertCell(-1);
    315             td1.innerHTML = arguments[2];
    316             //
    317             var td2 = tblScoreRow.appendChild(document.createElement("td"));
    318             td2.innerHTML = arguments[3];
    319             //
    320             var td3 = tblScoreRow.insertCell(-1);
    321             //第一种:显示传参
    322             td3.innerHTML = "<a href='javascript:Modified("sco"," + arguments[1] + ");'>修改</a>";
    323         };
    324         function InsertRowTotblStu() {
    325             var tblStudentRow = tblStudent.insertRow(arguments[0]);//arguments[0]=row的索引
    326             //tblStudentRow.setAttribute("name", arguments[0]);
    327 
    328             tblStudentRow.id = "stu" + arguments[1];
    329             var td0 = tblStudentRow.insertCell(-1);
    330             td0.innerHTML = arguments[1];
    331             var td1 = tblStudentRow.insertCell(-1);
    332             td1.innerHTML = arguments[2];
    333             var td2 = tblStudentRow.insertCell(-1);
    334             td2.innerHTML = arguments[3];
    335             var td3 = tblStudentRow.insertCell(-1);
    336             td3.innerHTML = arguments[4];
    337             var td4 = tblStudentRow.insertCell(-1);
    338             td4.innerHTML = arguments[5];
    339             var td5 = tblStudentRow.insertCell(-1);
    340             td5.innerHTML = GetDateFromJsonDate(arguments[6]);
    341             var td6 = tblStudentRow.insertCell(-1);
    342             //第二种:根据表格行获取单元格值。
    343             td6.innerHTML = "<a href='javascript:Modified("stu"," + arguments[1] + ");'>修改</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:Delete(" + arguments[1] + ");'>删除</a>";
    344         };
    345         function JsonStrToTable() {//接受数据函数
    346             var arr = arguments[0].split(" ");
    347             //每次回来数据都更新页数
    348             pageCount = parseInt(arr[1]);
    349             var pIndex = parseInt(arr[2]);
    350             //也可以
    351             var json = JSON.parse(arr[0]);
    352             //var json = eval(arguments[0]);   
    353             if (json != null) {//为防止删除后的出错 
    354                 if (json != undefined) {//对eval的判断
    355                     if (json.length > 0) {
    356                         if (json[0].Name == undefined) {
    357                             RemoveRowToTable(tblScore);
    358                             //向表格里插入行
    359                             for (var i = 0; i < json.length ; i++) {
    360                                 //tblScore.rows.length :自动增长的
    361                                 InsertRowTotblSco(tblScore.rows.length - 1, json[i].Id, json[i].Math, json[i].English);
    362                             }
    363                             //如果在这里同时插入pageBar当然没问题,pageCount已经初始化了
    364                             //但是请求页码值无法确定。
    365                             Paging("pageBarSco", pIndex, "NavigateOnClick", "sco");
    366                         } else {
    367                             //清空不需要的数据
    368                             RemoveRowToTable(tblStudent);
    369                             for (var i = 0; i < json.length; i++) {
    370                                 //{"sId":{"Id":1,"Math":null,"English":40},
    371                                 // "Id":1,"Name":"张夏槐",
    372                                 // "Age":9,"Gender":"女","CID":2,
    373                                 // "BirthDay":"\/Date(308592000000)\/"},
    374                                 InsertRowTotblStu(tblStudent.rows.length - 1, json[i].Id, json[i].Name, json[i].Age, json[i].Gender, json[i].CID, json[i].BirthDay);
    375                             }
    376                             Paging("pageBarStu", pIndex, "NavigateOnClick", "stu");
    377                         }
    378                     }
    379                 }
    380             }
    381             ////
    382             //pageCount = false;
    383         };
    384         function RequestPageByIndexAndName() {
    385             function cm() {
    386                 /*
    387                        var xhr = GetXHR();
    388                        //重复利用可以用 参数化
    389                        xhr.open("get", "SList.ashx?pi=" + arguments[0] + "&name=" + arguments[1], true);
    390                        //http://localhost:1030/List.aspx?pI=1  (Cache)
    391                        xhr.setRequestHeader("If-Modified-Since", "0");
    392                        xhr.onreadystatechange = function () {
    393                            if (xhr.readyState == 4) {
    394                                if (xhr.status == 200) {
    395                                    //如果是值是空 json数组是null ,而不是 ""=""
    396                                    var cont = xhr.responseText;//{"Id":1,"Math":null,"English":40}
    397                                    //将json 字符串传入-->
    398                                    JsonStrToTable(cont);
    399                                } else {
    400                                    alert("数据错误。");
    401                                }
    402                            }
    403                        };
    404                        xhr.send(null);
    405                        */
    406             };                                      //Error:说明若"Error",未找到函数。
    407             Request("get", "SList.ashx?pi=" + arguments[0] + "&name=" + arguments[1], true, JsonStrToTable, Error, null);
    408             //如果在这里同时插入pageBar会出现问题,pageCount还没有值。
    409             ////只能用线程性接受pageCount
    410             //var tid = setInterval(function () {
    411             //    if (pageCount != false) {
    412 
    413             //    }
    414             //}, 200);
    415         };
    416         //被请求页
    417         function NavigateOnClick() {
    418             //发送请求
    419             var pi = arguments[0];
    420             if (isNaN(pi))
    421                 pi = parseInt(GetObject("pGoto").value);
    422             if (pi < 1)
    423                 pi = 1;
    424             else if (pi > pageCount)
    425                 pi = pageCount;
    426             RequestPageByIndexAndName(pi, arguments[1]);
    427         };
    428         window.onload = function () {
    429             tblStudent = GetObject("tblStu");
    430             tblScore = GetObject("tblSco");
    431             RequestPageByIndexAndName(1, "sco");//动态删除后分页有Bug
    432             RequestPageByIndexAndName(1, "stu");
    433             ////向PageBar位置输出 
    434             //pageNavigatorPanel("pageBarSco");
    435             //pageNavigatorPanel("pageBarStu");
    436         };
    437     </script>
    438 </head>
    439 <body>
    440     <div>
    441         <p>学生信息列表</p>
    442         <table cellspacing="0" id="tblSco" class="center" style=" 620px; margin-left: -310px;">
    443             <tr>
    444                 <td colspan="4" style="padding-bottom: 20px; border: none;">成绩表</td>
    445             </tr>
    446             <tr>
    447                 <td>id</td>
    448                 <td>Math</td>
    449                 <td>English</td>
    450                 <td>Edit</td>
    451             </tr>
    452             <!--<%--用另一种方式了--%>
    453          <%----%>   <%=sbSco==null?"":sbSco.ToString() %>-->
    454             <tr>
    455                 <!-- <td>分页</td>-->
    456                 <td colspan="4">
    457                     <div id="pageBarSco"></div>
    458                     <!--                    <a title="首页" class="page" id="pFirst" href="#" style="">首页</a>
    459                     <a title="上一页" class="page" id="pPrevious" href="#">上一页</a>
    460                     <a title="" class="page pageB" id="" href="#">8</a>
    461                     <a title="" class="page pageB" id="A5" href="#">9</a>
    462                     <a title="" class="page pageB" id="A6" href="#">10</a>
    463                     <a title="" class="page pageB" id="A7" href="#">11</a>
    464                     <a title="" class="page pageB" id="A8" href="#">12</a>
    465                     <a title="下一页" class="page" id="pNext" href="#">下一页</a>
    466                     <a title="尾页" class="page" id="pTrailer" href="#">尾页</a>
    467             &nbsp;&nbsp;至第<input type="text" id="pGoto" style="border:1px solid rgb(206,206,206); 31px;height:19px;margin:1px 0;text-align:center;" />页-->
    468                 </td>
    469                 <!--   <td>分页</td>-->
    470             </tr>
    471         </table>
    472         <hr style=" 57%; color: #b200ff;" />
    473         <table cellspacing="0" id="tblStu" class="center" style=" 760px; margin: 25px 0 0 -380px;">
    474             <tr>
    475                 <td colspan="6" style="border: none; text-align: left; padding-left: 16px;">学生表</td>
    476                 <td style="border: none;"><a href="javascript:Add();">增加</a></td>
    477             </tr>
    478             <tr>
    479                 <td style="">id</td>
    480                 <td>Name</td>
    481                 <td>Age</td>
    482                 <td>Gender</td>
    483                 <td>ClassId</td>
    484                 <td>Birthday</td>
    485                 <td>Edit</td>
    486             </tr>
    487             <!--<%--用另一种方式了--%>
    488          <%----%>   <%=sbStu==null?"":sbStu.ToString() %>-->
    489             <tr>
    490                 <td>分页</td>
    491                 <td colspan="5">
    492                     <div id="pageBarStu"></div>
    493                     <!--                    <a title="首页" class="page" id="A1" href="#">首页</a>
    494                     <a title="上一页" class="page" id="A2" href="#">上一页</a>
    495                     <a title="下一页" class="page" id="A3" href="#">下一页</a>
    496                     <a title="尾页" class="page" id="A4" href="#">尾页</a>          -->
    497                 </td>
    498                 <td>分页</td>
    499             </tr>
    500         </table>
    501     </div>
    502     <hr style=" 70%; color: #b200ff; margin-top: 2%;" />
    503     <p style="font-size: medium; padding: 15px 0;">主要练习异步对象,分页</p>
    504     <!--    有了AJAX就不用提交表单了。-->
    505     <!--    <form method="post" action="NonQuery.ashx">-->
    506     <div id="stuAdd" class="Add" style=" 400px; height: 150px; margin-left: -200px; margin-top: -75px;">
    507         姓名:<input type="text" id="txtName" />
    508         年龄:<input type="text" id="txtAge" />
    509         性别:<input type="text" id="txtGender" /><br />
    510         班级ID:<input type="text" id="txtCID" /><br />
    511         出生日期:<input type="text" id="txtBirthday" /><br />
    512         <div class="button">
    513             <!--不能写成 submit 不然后台得不到数据-->
    514             <input type="button" value="确定" onclick="OK(1);" /><input type="button" value="取消" onclick="    Cancel('stuAdd');" />
    515         </div>
    516     </div>
    517     <!--    </form>-->
    518     <!--练习储存过程的@@identity
    519     <form method="post" action="NonQuery.ashx">-->
    520     <div id="scoAdd" class="Add" style=" 280px; height: 126px; margin: -63px 0 0 -140px;">
    521         id:<input type="text" id="txtId" readonly="readonly" /><br />
    522         Math:<input type="text" id="txtMath" /><br />
    523         English:<input type="text" id="txtEnglish" />
    524         <div class="button" id="Action">
    525             <!--不能写成 submit 不然后台得不到数据-->
    526             <input type="button" value="确定" onclick="OK(2);" /><!--<input type="button" value="取消" onclick="Cancel();" />-->
    527         </div>
    528     </div>
    529     <!--    </form>-->
    530 </body>
    531 </html>
    View Code

    SList.ashx

     1 <%@ WebHandler Language="C#" Class="SList" %>
     2 
     3 using System;
     4 using System.Web;
     5 using System.Web.Script.Serialization;
     6 using System.Collections.Generic;
     7 
     8 public class SList : IHttpHandler
     9 {
    10     private Web.BLL.TransferAction action = null;
    11 
    12     private int rowCount, pageCount;
    13     private int pageSize = 5, pageIndex;
    14 
    15     public void ProcessRequest(HttpContext context)
    16     {
    17         context.Response.ContentType = "text/html";
    18 
    19         //不能判断是get,post方式下取值
    20         string pIndex = context.Request.Params["pi"];
    21         string tblName = context.Request.QueryString["name"];
    22         if (pIndex != null && tblName != null)
    23         {
    24             pageIndex = int.Parse(pIndex);
    25             JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
    26 
    27             if (tblName == "sco")//"stu"
    28             {
    29                 List<Web.Model.MyScore> lsSco = this.GetList<Web.Model.MyScore>(out rowCount, out pageCount, pageIndex, pageSize);
    30                 //序列化为Json字符串。
    31                 context.Response.Write(jsSerializer.Serialize(lsSco));
    32             }
    33             else
    34             {
    35                 List<Web.Model.MyStudent> lsStu = this.GetList<Web.Model.MyStudent>(out rowCount, out pageCount, pageIndex, pageSize);
    36                 context.Response.Write(jsSerializer.Serialize(lsStu));
    37             }
    38         }
    39         //看客户端能接受到pageCount?  YES//别忘了缓冲区。
    40         //if (pageIndex > pageCount)
    41         //    pageIndex = pageCount;
    42         context.Response.Write(" " + pageCount + " " + pageIndex);
    43     }
    44     public List<T> GetList<T>(out int rowCount, out int pageCount, int pageIndex, int pageSize = 5)
    45     {
    46         //T a = T() ;
    47         List<T> lt = new List<T>();
    48         action = new Web.BLL.TransferAction();
    49         if (lt is List<Web.Model.MyScore>)
    50         {
    51             return action.GetListSco(out rowCount, out pageCount, pageIndex, pageSize) as List<T>;
    52         }
    53         else
    54         {
    55             return action.GetListStu(out rowCount, out pageCount, pageIndex, pageSize) as List<T>;
    56         }
    57     }
    58 
    59 }
    View Code

    NonQuery.ashx

     1 <%@ WebHandler Language="C#" Class="NonQuery" %>
     2 
     3 using System;
     4 using System.Web;
     5 
     6 public class NonQuery : IHttpHandler
     7 {
     8     private int result = -1;
     9     private Web.BLL.TransferAction action = null;
    10 
    11     public void ProcessRequest(HttpContext context)
    12     {
    13         context.Response.ContentType = "text/html";
    14         //临时变量
    15         int tmp; DateTime dt;
    16         Web.Model.ActionBehavior AB; //null;//枚举不是引用类型
    17         //是否可以用到  ActionBehavior
    18         //不能用传过来的是字符串,不是类型。
    19         //删除(级联)
    20         string id = context.Request.Form["id"];
    21         // string id = context.Request.Params["id"];
    22         // string id = context.Request.QueryString["id"];
    23         //添加(学生)
    24         string name = context.Request.Form["name"];
    25         //添加(成绩)
    26         string sid = context.Request.Form["sid"];
    27 
    28         //修改 action=modify
    29         string actid = context.Request.QueryString["actionId"];
    30         AB = Web.Model.ActionBehavior.Add;
    31         if (actid != null)
    32             AB = Web.Model.ActionBehavior.Modify;
    33 
    34         //用一个 action 对象可以吗?:肯定不行
    35         if (id != null)
    36         {
    37             action = new Web.BLL.TransferAction();
    38             result = action.ExecuteNonQuery(Web.Model.ActionBehavior.Delete, new Web.Model.MyStudent() { Id = int.Parse(id) });
    39         }
    40         else if (name != null)
    41         {
    42             string age = context.Request.Form["age"];
    43             string gender = context.Request.Form["gender"];
    44             string cid = context.Request.Form["cid"];
    45             string birthday = context.Request.Form["birthday"];
    46 
    47             action = new Web.BLL.TransferAction();
    48             result = action.ExecuteNonQuery<Web.Model.MyStudent>(AB,
    49                 new Web.Model.MyStudent()
    50                 {
    51 
    52                     Id = actid == null ? 0 : int.Parse(actid),
    53                     Name = name == "" ? null : name,
    54                     Age = int.TryParse(age, out tmp) == true ? (int?)tmp : null,
    55                     Gender = (gender == "" || gender == "") ? (char?)char.Parse(gender) : null,
    56                     CID = int.TryParse(cid, out tmp) == true ? (int?)tmp : null,
    57                     BirthDay = DateTime.TryParse(birthday, out dt) == true ? (DateTime?)dt : null
    58                 });
    59         }
    60         else if (sid != null)
    61         {
    62             string math = context.Request.Form["math"];
    63             string english = context.Request.Form["english"];
    64 
    65             action = new Web.BLL.TransferAction();
    66 
    67             result = action.ExecuteNonQuery<Web.Model.MyScore>(AB,
    68                 new Web.Model.MyScore()
    69                 {
    70                     Id = int.Parse(sid),
    71                     Math = int.TryParse(math, out tmp) == true ? (int?)tmp : null,
    72                     English = int.TryParse(english, out tmp) == true ? (int?)tmp : null
    73                 });
    74         }
    75         //结果返回
    76         context.Response.Write(result);
    77     }
    78 
    79 }
    View Code

    DataAction.cs

      1     public class DataAction
      2     {
      3         private List<Web.Model.MyStudent> ltStu = null;
      4         private List<Web.Model.MyScore> ltSco = null;
      5         public DataAction()
      6         {
      7             ltStu = new List<Web.Model.MyStudent>();
      8         }
      9 
     10         public List<Web.Model.MyStudent> GetListStu(out int rowCount, out int pageCount, int pageIndex, int pageSize = 5)
     11         {
     12             rowCount = pageCount = -1;
     13             //定义参数
     14             System.Data.SqlClient.SqlParameter[] param = {new System.Data.SqlClient.SqlParameter( "@pageIndex",pageIndex),
     15                     new System.Data.SqlClient.SqlParameter("@pageSize",pageSize),
     16                     new System.Data.SqlClient.SqlParameter("@rowCount",rowCount),
     17                     new System.Data.SqlClient.SqlParameter("@pageCount",pageCount) };
     18             //方向
     19             param[2].Direction = System.Data.ParameterDirection.Output;
     20             param[3].Direction = System.Data.ParameterDirection.Output;
     21 
     22             using (System.Data.SqlClient.SqlDataReader reader = SqlHelper.ExecuteGetPaging("pro_MyStudent", param))
     23             {
     24                 if (reader.HasRows)
     25                 {
     26                     Web.Model.MyStudent stu = null;
     27                     ltStu = new List<Model.MyStudent>();
     28                     while (reader.Read())
     29                     {
     30                         //由于储存过程
     31                         //  select * from (
     32                         //      select row_number() over(order by id) as IsIdentity,* from MyStudent
     33                         //  ) as tbl where tbl.IsIdentity between * and * 
     34                         //增加了一列IsIdentity
     35                         stu = new Web.Model.MyStudent();
     36                         stu.Id = int.Parse(reader[1].ToString());
     37                         stu.sId = this.GetScore(stu.Id);
     38                         stu.Name = reader.IsDBNull(2) ? null : reader[2].ToString();
     39                         stu.Age = reader.IsDBNull(3) ? null : (int?)reader.GetInt32(3);
     40                         stu.Gender = reader.IsDBNull(4) ? null : (char?)char.Parse(reader[4].ToString());
     41                         stu.CID = reader.IsDBNull(5) ? null : (int?)int.Parse(reader[5].ToString());
     42                         stu.BirthDay = reader.IsDBNull(6) ? null : (DateTime?)reader.GetDateTime(6);
     43                         ltStu.Add(stu);
     44                     }
     45 
     46                     //为什么???
     47                     //结束当前游标 (指向下一个程序集。)
     48                     if (reader.NextResult())
     49                     {
     50                         //while (reader.Read())
     51                         //{
     52                         //    rowCount = int.Parse(param[2].Value.ToString());
     53                         //    pageCount = Convert.ToInt32(param[3].Value);
     54                         //}
     55                     }
     56                     // object a=reader[0];
     57                     rowCount = int.Parse(param[2].Value.ToString());
     58                     pageCount = Convert.ToInt32(param[3].Value);
     59                 }
     60                 return ltStu;
     61             }
     62         }
     63 
     64         public List<Web.Model.MyScore> GetListSco(out int rowCount, out int pageCount, int pageIndex, int pageSize = 5)
     65         {
     66             rowCount = pageCount = -1;
     67             using (System.Data.DataTable dt = SqlHelper.ExecuteGetPaging("pro_MyScore", out rowCount, out pageCount, pageIndex, pageSize))
     68             {
     69                 if (dt.Rows.Count > 0)
     70                 {
     71                     ltSco = new List<Model.MyScore>();
     72                     foreach (System.Data.DataRow item in dt.Rows)
     73                     {
     74                         Web.Model.MyScore score = new Model.MyScore();
     75                         score.Id = int.Parse(item[0].ToString());
     76                         score.Math = item.IsNull(1) ? null : (int?)int.Parse(item[1].ToString());
     77                         score.English = item.IsNull(2) ? null : (int?)int.Parse(item[2].ToString());
     78                         ltSco.Add(score);
     79                     }
     80                 }
     81                 return ltSco;
     82             }
     83         }
     84 
     85         public Web.Model.MyScore GetScore(int id)
     86         {
     87             Web.Model.MyScore score = null;
     88             string sql = "select * from MyScore where id=@id";
     89             System.Data.SqlClient.SqlParameter[] param =
     90             {
     91                 new System.Data.SqlClient.SqlParameter("@id",id),
     92             };
     93 
     94             using (System.Data.DataTable dt = SqlHelper.ExecuteDataTable(sql, param))
     95             {
     96                 if (dt.Rows.Count > 0)
     97                 {
     98                     score = new Web.Model.MyScore();
     99                     System.Data.DataRow row = dt.Rows[0];
    100                     score.Id = int.Parse(row[0].ToString());
    101                     score.Math = row.IsNull(1) ? null : (int?)int.Parse(row[1].ToString());
    102                     score.English = row.IsNull(2) ? null : (int?)int.Parse(row[2].ToString());
    103                 } return score;
    104             }
    105         }
    106         public Web.Model.MyStudent GetStudent(int id)
    107         {
    108             Web.Model.MyStudent student = null;
    109             string sql = "select * from MyStudent where id=@id";
    110             System.Data.SqlClient.SqlParameter[] param =
    111             {
    112                 new System.Data.SqlClient.SqlParameter("@id",id),
    113             };
    114             using (System.Data.SqlClient.SqlDataReader reader = SqlHelper.ExecuteReader(sql, param))
    115             {
    116                 if (reader.HasRows)
    117                 {
    118                     student = new Web.Model.MyStudent();
    119                     while (reader.Read())
    120                     {
    121                         student.Id = reader.GetInt32(0);
    122                         student.sId = this.GetScore(student.Id);
    123                         student.Name = reader.IsDBNull(1) ? null : reader.GetString(1);
    124                         student.Age = reader.IsDBNull(2) ? null : (int?)reader.GetInt32(2);
    125                         student.Gender = reader.IsDBNull(3) ? null : (char?)Convert.ToChar(reader[3]);
    126                         student.CID = reader.IsDBNull(4) ? null : (int?)int.Parse(reader[4].ToString());
    127                         student.BirthDay = reader.IsDBNull(5) ? null : (DateTime?)DateTime.Parse(reader[5].ToString());
    128                     }
    129                 }
    130                 return student;
    131             }
    132         }
    133 
    134         public int ExecuteNonQuery<T>(Web.Model.ActionBehavior behavior, T S)
    135         {
    136             string sql = string.Empty;
    137             System.Data.SqlClient.SqlParameter[] param = null;
    138             if (S is Web.Model.MyStudent)
    139             {
    140                 Web.Model.MyStudent stu = S as Web.Model.MyStudent;
    141                 switch (behavior)
    142                 {
    143                     case Web.Model.ActionBehavior.Add:
    144                         // int tmp = -1;
    145                         //sql = "insert into MyStudent values(@n,@a,@g,@ci,@b)";
    146                         sql = "pro_GetIdentityFromMyStu";
    147                         //切记: 参数名要和字段名(储存过程)一致和参数要加@
    148                         param = new System.Data.SqlClient.SqlParameter[]{
    149                             new System.Data.SqlClient.SqlParameter("@name",stu.Name==null?DBNull.Value:(object)stu.Name),
    150                             new System.Data.SqlClient.SqlParameter("@age",stu.Age==null?DBNull.Value:(object)stu.Age),
    151                             new System.Data.SqlClient.SqlParameter("@gender",stu.Gender==null?DBNull.Value:(object)stu.Gender),
    152                             new System.Data.SqlClient.SqlParameter("@classId",stu.CID==null?DBNull.Value:(object)stu.CID),
    153                             new System.Data.SqlClient.SqlParameter("@birthday",stu.BirthDay==null?DBNull.Value:(object)stu.BirthDay)
    154                           // new System.Data.SqlClient.SqlParameter("@identity",tmp)
    155                         };
    156                         //但是可以带出参数的准确值
    157                         // param[5].Direction = System.Data.ParameterDirection.Output;
    158                         // select @identity=@@IDENTITY 这个储存过程没有产生结果集
    159                         //System.Data.DataTable  a = SqlHelper.ExecuteDataTable(sql, true, param);
    160                         //Convert.ToInt32(param[5].Value);
    161                         //修改为  select @@IDENTITY 得到程序集
    162                         return Convert.ToInt32(SqlHelper.ExecuteDataTable(sql, true, param).Rows[0][0]);
    163                     case Web.Model.ActionBehavior.Modify:
    164                         sql = "update MyStudent set Name=@n,Age=@a,Gender=@g,ClassId=@ci,Birthday=@b where id=@id";
    165                         param = new System.Data.SqlClient.SqlParameter[]{
    166                             new System.Data.SqlClient.SqlParameter("@id",stu.Id),
    167                             new System.Data.SqlClient.SqlParameter("@n",stu.Name==null?DBNull.Value:(object)stu.Name),
    168                             new System.Data.SqlClient.SqlParameter("@a",stu.Age==null?DBNull.Value:(object)stu.Age),
    169                             new System.Data.SqlClient.SqlParameter("@g",stu.Gender==null?DBNull.Value:(object)stu.Gender),
    170                             new System.Data.SqlClient.SqlParameter("@ci",stu.CID==null?DBNull.Value:(object)stu.CID),
    171                             new System.Data.SqlClient.SqlParameter("@b",stu.BirthDay==null?DBNull.Value:(object)stu.BirthDay)
    172                         };
    173                         break;
    174                     case Web.Model.ActionBehavior.Delete:
    175                         sql = "delete from MyStudent where id=@id";//设置的是级联删除
    176                         param = new System.Data.SqlClient.SqlParameter[] { new System.Data.SqlClient.SqlParameter("@id", stu.Id) };
    177                         break;
    178                 }
    179             }
    180             else
    181             {
    182                 Web.Model.MyScore score = S as Web.Model.MyScore;
    183                 switch (behavior)
    184                 {
    185                     case Web.Model.ActionBehavior.Modify:
    186                         sql = "update MyScore set Math=@m,English=@e where id=@id";
    187                         param = new System.Data.SqlClient.SqlParameter[] {
    188                             new System.Data.SqlClient.SqlParameter("@id",score.Id),
    189                         new System.Data.SqlClient.SqlParameter("@m",score.Math==null?DBNull.Value:(object)score.Math),
    190                         new System.Data.SqlClient.SqlParameter("@e",score.English==null?DBNull.Value:(object)score.English)};
    191                         break;
    192                     case Web.Model.ActionBehavior.Add:
    193                         sql = "insert into MyScore values(@id,@m,@e)";
    194                         param = new System.Data.SqlClient.SqlParameter[] {
    195                         new System.Data.SqlClient.SqlParameter("@id",score.Id),
    196                         new System.Data.SqlClient.SqlParameter("@m",score.Math==null?DBNull.Value:(object)score.Math),
    197                         new System.Data.SqlClient.SqlParameter("@e",score.English==null?DBNull.Value:(object)score.English)};
    198                         break;
    199                     /*  case Web.Model.ActionBehavior.Delete:
    200                           sql = "delete from MyScore where id";*/
    201                 }
    202             }
    203             return SqlHelper.ExecuteNonQuery(sql, param);
    204         }
    205     }
    View Code

    SqlHelper.cs

      1     public static class SqlHelper
      2     {
      3         private readonly static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
      4 
      5         #region 这两个方法可以和起来
      6 
      7         public static System.Data.SqlClient.SqlDataReader ExecuteReader(string sql, params System.Data.SqlClient.SqlParameter[] param)
      8         {
      9             System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr);
     10 
     11             using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con))
     12             {
     13                 if (param != null)
     14                 {
     15                     cmd.Parameters.AddRange(param);
     16                 }
     17                 con.Open();
     18                 return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
     19             }
     20         }
     21         //public static System.Data.SqlClient.SqlDataReader ExecuteGetPaging(out int rowCount, out int pageCount, string proName, int pageIndex, int pageSize = 5)
     22         //{
     23         public static System.Data.SqlClient.SqlDataReader ExecuteGetPaging(string proName, params System.Data.SqlClient.SqlParameter[] param)
     24         {
     25             //System.Data.SqlClient.SqlDataReader reader = null;
     26             //rowCount = pageCount = -1;
     27             System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr);
     28 
     29             using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(proName, con))
     30             {
     31                 cmd.CommandType = System.Data.CommandType.StoredProcedure;
     32                 //System.Data.SqlClient.SqlParameter[] param = {new System.Data.SqlClient.SqlParameter( "@pageIndex",pageIndex),
     33                 //        new System.Data.SqlClient.SqlParameter("@pageSize",pageSize),
     34                 //        new System.Data.SqlClient.SqlParameter("@rowCount",rowCount),
     35                 //        new System.Data.SqlClient.SqlParameter("@pageCount",pageCount) };
     36                 //param[2].Direction = System.Data.ParameterDirection.Output;
     37                 //param[3].Direction = System.Data.ParameterDirection.Output;
     38                 if (param != null)
     39                 {
     40                     cmd.Parameters.AddRange(param);
     41                 }
     42                 con.Open();
     43                 //reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
     44                 //return reader;
     45                 return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
     46             }
     47         }
     48         #endregion
     49         #region 和起来的ExecuteReader
     50 
     51         public static System.Data.SqlClient.SqlDataReader ExecuteReader(string sql, bool isProc, params System.Data.SqlClient.SqlParameter[] param)
     52         {
     53             System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr);
     54             using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con))
     55             {
     56                 if (isProc)
     57                     cmd.CommandType = System.Data.CommandType.StoredProcedure;
     58                 if (param != null)
     59                     cmd.Parameters.AddRange(param);
     60                 con.Open();
     61                 return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
     62             }
     63         }
     64         #endregion
     65 
     66         public static System.Data.DataTable ExecuteDataTable(string sql, params System.Data.SqlClient.SqlParameter[] param)
     67         {
     68             System.Data.DataTable dt = new System.Data.DataTable();
     69             using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(sql, connstr))
     70             {
     71                 if (param != null)
     72                 {
     73                     adapter.SelectCommand.Parameters.AddRange(param);
     74                 }
     75                 adapter.Fill(dt);
     76                 return dt;
     77             }
     78         }
     79 
     80         public static System.Data.DataTable ExecuteGetPaging(string proName, out int rowCount, out int pageCount, int pageIndex, int pageSize = 5)
     81         {
     82             //out特性
     83             rowCount = pageCount = -1;
     84             System.Data.DataTable dt = new System.Data.DataTable();
     85             using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(proName, connstr))
     86             {
     87                 //查询命令类型
     88                 adapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
     89                 //参数放在外面是否更合适呢?
     90                 System.Data.SqlClient.SqlParameter[] param = 
     91                 {
     92                         new System.Data.SqlClient.SqlParameter("@pageIndex",pageIndex),
     93                         new System.Data.SqlClient.SqlParameter("@pageSize",pageSize),
     94                         new System.Data.SqlClient.SqlParameter("@rowCount",rowCount),
     95                         new System.Data.SqlClient.SqlParameter("@pageCount",pageCount)
     96                  };
     97                 adapter.SelectCommand.Parameters.AddRange(param);
     98                 //参数方向
     99                 param[2].Direction = System.Data.ParameterDirection.Output;
    100                 param[3].Direction = System.Data.ParameterDirection.Output;
    101                 adapter.Fill(dt);
    102                 //为确保转换成功不能使用强制类型转换---参数赋值
    103                 // rowCount = param[2].Value;
    104                 rowCount = Convert.ToInt32(param[2].Value);
    105                 pageCount = int.Parse(param[3].Value.ToString());
    106 
    107                 return dt;
    108             }
    109         }
    110 
    111         public static System.Data.DataTable ExecuteDataTable(string sql, bool isProc, params System.Data.SqlClient.SqlParameter[] param)
    112         {
    113             System.Data.DataTable dt = new System.Data.DataTable();
    114             using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(sql, connstr))
    115             {
    116                 if (isProc)//执行的是插入的储存过程,给SelectCommand赋值可以吗? :可以
    117                     adapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
    118                 if (param != null)
    119                     adapter.SelectCommand.Parameters.AddRange(param);
    120                 adapter.Fill(dt);
    121                 return dt;
    122             }
    123         }
    124 
    125         public static int ExecuteNonQuery(string sql, params System.Data.SqlClient.SqlParameter[] param)
    126         {
    127             using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr))
    128             {
    129                 using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con))
    130                 {
    131                     if (param != null)
    132                         cmd.Parameters.AddRange(param);
    133                     con.Open();
    134                     //若级联插入出错不会返回-1,没有报错 会返回状态码 500=服务器内部错误,前台处理一下
    135                     int a=cmd.ExecuteNonQuery();
    136                     return a;
    137                 }
    138             }
    139         }
    140     }
    View Code

    ActionBehavior.cs

    1     public enum ActionBehavior
    2     {
    3         Add,Modify,Delete
    4     }
    View Code

    项目文件:https://pan.baidu.com/s/1i31e65f

  • 相关阅读:
    腾讯QQ强制下线,每天可能强抢会员300万元
    visual studio 2010 winform程序不能添加对system.web的引用
    一个用来将Excel中同一个人的多行记录中的特定列合并到第一行的宏
    很希望看到微软来一次“因为QQ未经用户允许扫描硬盘,在所有window平台拒绝运行QQ”
    windows2003的数据执行保护会造成无法正常安装SQL SERVER
    改变jboss部署目录(虚拟目录)
    SecureCRT6.5.0英文版,提示数据库里没有找到防火墙"无"
    spring注解事务
    windows下查看端口被哪个程序占用
    union和union all区别
  • 原文地址:https://www.cnblogs.com/wjshan0808/p/3681765.html
Copyright © 2011-2022 走看看