【Jqurey EasyUI+Asp.net】----DataGrid資料繫結,以及增、刪、改(SQL)

來源:互聯網
上載者:User

標籤:--   var   ring   system   res   javascrip   rom   1.3   ret   

也懶得打其他字了,直接進入主題吧

1.首先,資料表Rex_Test

ID
int
自增
tName
varchar(10)
姓名
tEmail
varchar(80)
郵箱


2.至於代碼裡的Jqurey EasyUI包就直接去官網下載吧。當然其他地方也行,這裡就不多做說明了。


3.前台顯示頁面

Default.aspx

<span style="font-size:14px;"><head>    <title>myWeb</title>    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.6/themes/default/easyui.css">    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.6/themes/icon.css">    <link rel="stylesheet" type="text/css" href="demo.css">    <script type="text/javascript" src="jquery-easyui-1.3.6/jquery.min.js"></script>    <script type="text/javascript" src="jquery-easyui-1.3.6/jquery.easyui.min.js"></script></head><body >    <table id="dg" class="easyui-datagrid" style="width: 700px; height: 300px" data-options="rownumbers:true,onClickRow:ClickRow,singleSelect:true,border:false,pagination:true,url:'Handler3.ashx'">        <thead>            <tr>                <th data-options="field:'ID',width:100">                    ID                </th>                <th data-options="field:'tName',width:100">                    姓名                </th>                <th data-options="field:'tEmail',width:100">                    郵箱                </th>            </tr>        </thead>    </table>    <div id="Div1" class="easyui-panel" title="form Fields" style="width: 1000px; height: 180px;        float: left;">        <table>            <tr>                <td>                    姓名:                </td>                <td>                    <input id="n" class="easyui-validatebox" type="text" name="name" data-options="required:true" />                </td>            </tr>            <tr>                <td>                    郵箱:                </td>                <td>                    <input id="pr" class="easyui-validatebox" type="text" name="price" data-options="required:true" />                </td>            </tr>            <tr>                <td>                    查詢:                </td>                <td>                    <input id="sear" class="easyui-validatebox" type="text" name="price" data-options="required:true" />                </td>            </tr>            <tr>                <td>                    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="add()">                        Add</a>                </td>                <td>                    <a href="#r" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="refresh()">Refresh</a>                     <a href="#r" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="del()">Delete</a>                                    </td>            </tr>        </table>    </div>    <ul id="tt" class="easyui-tree">    </ul>    <script type="text/javascript">        $(document).ready(function ()        {            $.ajax({                url: "Handler3.ashx",                type: "get",                dataType: "json",                error: function (request, message, ex)                {                    alert(message + request + ex);                },                success: function (returnValue)                {                    $("#tt").tree("loadData", returnValue);                }            })        });        function searchs()        {            $.ajax({                url: "refresh.ashx",                type: "post",                data: "fac=" + $("#sear").val(),                // data: "olditemid=" + $("#dg").datagrid("getSelected").ItemID + "&itemid=" + $("#ii").val(),                error: function (request, message, ex)                {                    alert(message + request + ex);                },                success: function (returnValue)                {                    alert(returnValue);                    $('#dg').datagrid('reload');                }            })        }        function add()        {            $.ajax({                url: "add.ashx",                type: "get",                data: "name=" + $("#n").val() + "&email=" + $("#pr").val(),                error: function (request, message, ex)                {                    alert(message + request + ex);                },                success: function (returnValue)                {                    alert(returnValue);                    $('#dg').datagrid('reload');                 }            })        }        function del()        {            $.ajax({                url: "del.ashx",                type: "get",                data: "id=" + $("#dg").datagrid("getSelected").ID,                error: function (request, message, ex)                {                    alert(message + request + ex);                },                success: function (returnValue)                {                    //                     alert(returnValue);                    $('#dg').datagrid('reload');                 }            })        }        function ClickRow(rowIndex, rowData)        {            //            alert('這是Name:' + rowData.Name + '這個是ID:' + rowData.ID);                        if (rowData) {                //document.getElementById("ii").value = rowData.ID;                document.getElementById("n").value = rowData.tName;                document.getElementById("pr").value = rowData.tEmail;            }        }        function refresh()        {            $.ajax({                url: "refresh.ashx",                type: "get",                data: "id=" + $("#dg").datagrid("getSelected").ID + "&name=" + $("#n").val() + "&email=" + $("#pr").val(),                // data: "olditemid=" + $("#dg").datagrid("getSelected").ItemID + "&itemid=" + $("#ii").val(),                error: function (request, message, ex)                {                    alert(message + request + ex);                },                success: function (returnValue)                {                    alert(returnValue);                    $('#dg').datagrid('reload');                 }            })        }    </script></body></html></span>


4. Handler3.ashx(初始綁定)

<span style="font-size:14px;"><%@ WebHandler Language="C#" Class="Handler3" %>using System;using System.Web;using System.Data;using System.Data.SqlClient;using System.Text;using System.IO;public class Handler3 : IHttpHandler {    public void ProcessRequest(HttpContext context)    {                   Query(context);    }    public void Query(HttpContext context)    {        //調用B層的方法從而擷取資料庫的Dataset          SqlHelp sqla = new SqlHelp();        string strfaca = "select * from Rex_Test";        DataSet ds = sqla.GetDataSet(strfaca);        //將Dataset轉化為Datable          DataTable dt = ds.Tables[0];        int count = dt.Rows.Count;        string strJson = Dataset2Json(ds, count);//DataSet資料轉化為Json資料          context.Response.Write(strJson);//返回給前台頁面          context.Response.End();    }    /// <summary>    /// DataSet轉換成Json格式     /// </summary>     /// <paramname="ds">DataSet</param>    ///<returns></returns>     public static string Dataset2Json(DataSet ds, int total = -1)    {        StringBuilder json = new StringBuilder();        foreach (DataTable dt in ds.Tables)        {            //{"total":5,"rows":[            json.Append("{\"total\":");            if (total == -1)            {                json.Append(dt.Rows.Count);            }            else            {                json.Append(total);            }            json.Append(",\"rows\":[");            json.Append(DataTable2Json(dt));            json.Append("]}");        }        return json.ToString();    }    /// <summary>     /// dataTable轉換成Json格式     /// </summary>     /// <paramname="dt"></param>     ///<returns></returns>     public static string DataTable2Json(DataTable dt)    {        StringBuilder jsonBuilder = new StringBuilder();        for (int i = 0; i < dt.Rows.Count; i++)        {            jsonBuilder.Append("{");            for (int j = 0; j < dt.Columns.Count; j++)            {                jsonBuilder.Append("\"");                jsonBuilder.Append(dt.Columns[j].ColumnName);                jsonBuilder.Append("\":\"");                jsonBuilder.Append(dt.Rows[i][j].ToString());                jsonBuilder.Append("\",");            }            if (dt.Columns.Count > 0)            {                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);            }            jsonBuilder.Append("},");        }        if (dt.Rows.Count > 0)        {            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);        }        return jsonBuilder.ToString();    }    public bool IsReusable    {        get        {            return false;        }    }}</span>

5.add.ashx(新增資料)


<span style="font-size:14px;"><%@ WebHandler Language="C#" Class="add" %>using System;using System.Web;public class add : IHttpHandler {    public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "text/plain";        string result = string.Empty;        string name = context.Request.QueryString["name"];        string email = context.Request.QueryString["email"];        SqlHelp sqla = new SqlHelp();        string sqlString = "insert into Rex_Test(tName,tEmail) values('"+name+"','"+email+"')";        bool aa = sqla.ExecuteNonQuery(sqlString);        sqla.SqlClose();        if (aa)        {            result = "加入紀錄成功";        }        context.Response.Write(result);    }    public bool IsReusable    {        get        {            return false;        }    }}</span>

6.del.ashx(刪除資料)

<span style="font-size:14px;"><%@ WebHandler Language="C#" Class="del" %>using System;using System.Web;public class del : IHttpHandler {    public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "text/plain";        string result = string.Empty;        string id = context.Request.QueryString["id"];        SqlHelp sqla = new SqlHelp();        string sqlString = "delete from Rex_Test where ID='" + id + "'";        bool aa = sqla.ExecuteNonQuery(sqlString);        sqla.SqlClose();        if (aa)        {            result = "刪除成功";        }        context.Response.Write(result);    }    public bool IsReusable    {        get        {            return false;        }    }}</span>

7.refresh.ashx(更新資料)

<span style="font-size:14px;"><%@ WebHandler Language="C#" Class="refresh" %>using System;using System.Web;public class refresh : IHttpHandler {    public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "text/plain";        string result = string.Empty;        string id = context.Request.QueryString["id"];        string name = context.Request.QueryString["name"];        string email = context.Request.QueryString["email"];        SqlHelp sqla = new SqlHelp();        string sqlString = "update  Rex_Test set tName='"+name+"',tEmail='"+email+"'  where ID='" + id + "'";        bool aa = sqla.ExecuteNonQuery(sqlString);        sqla.SqlClose();        if (aa)        {            result = "更新成功";        }        context.Response.Write(result);    }    public bool IsReusable    {        get        {            return false;        }    }}</span>

8.基本上這個樣子就差點兒相同了。更加細化的東西還沒來得及做,下次弄好了才發吧。

哦。對了,代碼裡的SqlHelp sqla = new SqlHelp();事實上就是個sql操作類,自己寫的,網上有非常多這樣的的SqlHelper。這個我就不貼出來了吧。

【Jqurey EasyUI+Asp.net】----DataGrid資料繫結,以及增、刪、改(SQL)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.