使用HTTP处理程序和jQuery在ASP.NET Web应用程序中的进行数据库操作

来源:互联网 发布:淘宝买的组装机怎么样 编辑:程序博客网 时间:2024/05/17 06:05

源代码下载:https://www.codeproject.com/KB/aspnet/CRUDOpeartionUsingJQuery/CrudOpeartionUsingJQuery.zip

1.引言

这篇文章将逐步介绍如何在ASP.NET应用程序中,使用HttpHandler和Jquery Ajax API中创建CRUD(创建,读取,更新,删除)数据库基本应用程序。本文侧重于介绍技术,对于网页界面没有进行精心设计,不过这对我们的技术介绍不影响,读者可根据自己的实际需求自行设计相应界面。

2. 需求

我们知道,使用Jquery Ajax API来制作HttpHandler的Ajax调用需要添加Jquery文件的引用。 您可以从http://jquery.com获取最新的Jquery文件,或者如果您使用的是VS2010,默认情况下它将在Web项目中可用。

3.实施方案

网页界面截图

首先,创建一个新的ASP.NET Web项目。
然后创建一个文件夹名称脚本和添加Jquery文件和一个Commonfunction.js空白的JavaScript文件。

增加数据库
在本项目中添加Sql Server数据库文件,然后创建如下图所示的Products表:
Products数据结构

现在,添加用于执行数据库操作的名为products的Class文件。 并将以下代码添加到该类文件中。

public class DbProducts{    SqlConnection _con = new SqlConnection    (ConfigurationManager.ConnectionStrings[1].ConnectionString);    public List<Product> GetProductDetails()    {        try        {            List<Product> _lstProducts = new List<Product>();            Product _Product = null;            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Select * From Products";            SqlDataReader _Reader = _cmd.ExecuteReader();            while (_Reader.Read())            {                _Product = new Product();                _Product.ProductID = Convert.ToInt32(_Reader["ProductID"]);                _Product.Name = _Reader["Name"].ToString();                _Product.Unit = _Reader["Unit"].ToString();                _Product.Qty = Convert.ToDecimal(_Reader["Qty"]);                _lstProducts.Add(_Product);            }            return _lstProducts;        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public string InsertProduct(Product _P)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Insert Into Products(Name,Unit,Qty)Values                    (@Name,@Unit,@Qty)";            _cmd.Parameters.Add(new SqlParameter("@Name", _P.Name));            _cmd.Parameters.Add(new SqlParameter("@Qty", _P.Qty));            _cmd.Parameters.Add(new SqlParameter("@Unit", _P.Unit));            if (_cmd.ExecuteNonQuery() > 0)                return "Record Successfully Saved";            else                return "Record not Affected to DataBase";        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public string UpdateProduct(Product _P)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Update Products set Name=@Name,Unit=@Unit,            Qty=@Qty Where ProductID=@ProductID";            _cmd.Parameters.Add(new SqlParameter("@Name", _P.Name));            _cmd.Parameters.Add(new SqlParameter("@Qty", _P.Qty));            _cmd.Parameters.Add(new SqlParameter("@Unit", _P.Unit));            _cmd.Parameters.Add(new SqlParameter("@ProductID", _P.ProductID));            if (_cmd.ExecuteNonQuery() > 0)                return "Record Successfully Updated";            else                return "Record not Affected to DataBase";        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public string DeleteProduct(int ProductID)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Delete From Products Where ProductID=@ProductID";            _cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));            if (_cmd.ExecuteNonQuery() > 0)                return "Records Successfully Delete";            else                return "Records not Affected to DataBase";        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }    public Product GetProductById(int ProductID)    {        try        {            if (_con.State != System.Data.ConnectionState.Open)                _con.Open();            SqlCommand _cmd = _con.CreateCommand();            _cmd.CommandText = "Select * From Products Where ProductID=@ProductID";            _cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));            SqlDataReader _Reader = _cmd.ExecuteReader();            Product _Product = null;            while (_Reader.Read())            {                _Product = new Product();                _Product.ProductID = Convert.ToInt32(_Reader["ProductID"]);                _Product.Name = _Reader["Name"].ToString();                _Product.Qty = Convert.ToDecimal(_Reader["Qty"]);                _Product.Unit = _Reader["Unit"].ToString();            }            return _Product;        }        catch (Exception ex)        {            throw ex;        }        finally        {            if (_con.State != System.Data.ConnectionState.Closed)                _con.Close();        }    }}public class Product{    private int _ProductID = 0;    public int ProductID    {        get { return _ProductID; }        set { _ProductID = value; }    }    private string _Name = string.Empty;    public string Name    {        get { return _Name; }        set { _Name = value; }    }    private string _Unit = string.Empty;    public string Unit    {        get { return _Unit; }        set { _Unit = value; }    }    private decimal _Qty = 0;    public decimal Qty    {        get { return _Qty; }        set { _Qty = value; }    }}

接下来,创建一个名为JsonResponse的类文件,该类文件用于以json格式序列化响应。 将以下代码添加到该文件中。

using System;using System.Collections.Generic;using System.Linq;using System.Web;public class JsonResponse{    private bool _IsSucess = false;    public bool IsSucess    {        get { return _IsSucess; }        set { _IsSucess = value; }    }    private string _Message = string.Empty;    public string Message    {        get { return _Message; }        set { _Message = value; }    }    private object _ResponseData = null;    public object ResponseData    {        get { return _ResponseData; }        set { _ResponseData = value; }    }    private string _CallBack = string.Empty;    public string CallBack    {        get { return _CallBack; }        set { _CallBack = value; }    }} 

现在,将以下HTML添加到Default.aspx的Body标签中,用于产品输入表单。

<asp:Label runat="server" ID="lblTime"></asp:Label><form id="form1" action="" method="post"><table cellpadding="2" cellspacing="2" border="1"width="400px"><tr style="background-color: Gray"> <td colspan="2" align="center"><b>Product Entry Form</b></td></tr><tr>   <td>      Product Name   </td>   <td>      <input type="text" id="txtName"style="width:250px"/>  </td></tr><tr>  <td>      Unit  </td>  <td>  <input type="text"id="txtUnit"style="width: 250px"/>  </td></tr><tr>  <td>      Qty  </td>  <td>    <input type="text"id="txtQty"style="width: 250px"/>   </td></tr><tr>  <td colspan="2" align="center">    <input type="button"id="butSave"value="Save"onclick="SaveProducts()"/>   </td> </tr></table><br/><br/>   <div id="ListingData">   </div></form>

并将以下脚本标签添加到头标签中:

<script src="Script/jquery-1.2.6.js" type="text/javascript"></script><script src="Script/CommonFunction.js" type="text/javascript"></script>

接下来添加名为Product List.ashx的处理程序文件,用于在使用Jquery调用时获取响应。 将以下代码添加到该文件中:

public class ProductList : IHttpHandler{    string MethodName = string.Empty;    string CallBackMethodName = string.Empty;    object Parameter = string.Empty;    DbProducts _DbProducts = new DbProducts();    public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "application/x-javascript";        MethodName = context.Request.Params["method"];        Parameter = context.Request.Params["param"];        CallBackMethodName = context.Request.Params["callbackmethod"];        switch (MethodName.ToLower())        {            case "getproducts":                context.Response.Write(GetDetails());                break;            case "getbyid":                context.Response.Write(GetById());                break;            case "insert":                context.Response.Write(Insert(context));                break;            case "update":                context.Response.Write(Update(context));                break;            case "delete":                context.Response.Write(Delete());                break;        }    }    public string GetDetails()    {        JsonResponse _response = new JsonResponse();        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =                       new System.Web.Script.Serialization.JavaScriptSerializer();        try        {            System.Collections.Generic.List&lt;product> _Products =                     _DbProducts.GetProductDetails();            _response.IsSucess = true;            _response.Message = string.Empty;            _response.CallBack = CallBackMethodName;            _response.ResponseData = _Products;        }        catch (Exception ex)        {            _response.Message = ex.Message;            _response.IsSucess = false;        }        return jSearializer.Serialize(_response);    }    public string GetById()    {        JsonResponse _response = new JsonResponse();        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =                     new System.Web.Script.Serialization.JavaScriptSerializer();        try        {            Product _Products = _DbProducts.GetProductById(Convert.ToInt32(Parameter));            _response.IsSucess = true;            _response.Message = string.Empty;            _response.CallBack = CallBackMethodName;            _response.ResponseData = _Products;        }        catch (Exception ex)        {            _response.Message = ex.Message;            _response.IsSucess = false;        }        return jSearializer.Serialize(_response);    }    public string Insert(HttpContext context)    {        JsonResponse _response = new JsonResponse();        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =                     new System.Web.Script.Serialization.JavaScriptSerializer();        try        {            Product _P = new Product();            _P.Name = context.Request.Params["name"].ToString();            _P.Unit = context.Request.Params["unit"].ToString();            _P.Qty = Convert.ToDecimal(context.Request.Params["Qty"].ToString());            _response.IsSucess = true;            _response.CallBack = CallBackMethodName;            _response.ResponseData = _DbProducts.InsertProduct(_P);            _response.Message = "SucessFully Saved";        }        catch (Exception ex)        {            _response.Message = ex.Message;            _response.IsSucess = false;        }        return jSearializer.Serialize(_response);    }    public string Update(HttpContext context)    {        JsonResponse _response = new JsonResponse();        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =                     new System.Web.Script.Serialization.JavaScriptSerializer();        try        {            Product _P = new Product();            _P.Name = context.Request.Params["name"].ToString();            _P.Unit = context.Request.Params["unit"].ToString();            _P.Qty = Convert.ToDecimal(context.Request.Params["Qty"].ToString());            _P.ProductID = Convert.ToInt32        (context.Request.Params["ProductID"].ToString());            _response.IsSucess = true;            _response.Message = "SucessFully Updated";            _response.CallBack = CallBackMethodName;            _response.ResponseData = _DbProducts.UpdateProduct(_P);        }        catch (Exception ex)        {            _response.Message = ex.Message;            _response.IsSucess = false;        }        return jSearializer.Serialize(_response);    }    public string Delete()    {        JsonResponse _response = new JsonResponse();        System.Web.Script.Serialization.JavaScriptSerializer jSearializer =                     new System.Web.Script.Serialization.JavaScriptSerializer();        try        {            _response.IsSucess = true;            _response.Message = "Record Successfully Deleted";            _response.CallBack = CallBackMethodName;            _response.ResponseData = _DbProducts.DeleteProduct(Convert.ToInt32(Parameter));        }        catch (Exception ex)        {            _response.Message = ex.Message;            _response.IsSucess = false;        }        return jSearializer.Serialize(_response);    }    public bool IsReusable    {        get        {            return false;        }    }}

现在,去Coomonfunction.js,将以下函数添加到该文件中。

function DoAjaxCall(parameter, datatype, data) {    jQuery.ajax({        type: 'POST',        url: "ProductList.ashx" + parameter,        data: data,        dataType: datatype,        success: function(data, textStatus) {            try {                var jsonData = (new Function("return " + data))()                if (jsonData.IsSucess) {                    eval(jsonData.CallBack + '(jsonData.ResponseData, jsonData.Message)');                }                else {                    alert(jsonData.Message + jsonData.IsSucess);                }            }            catch (err) {            }        },        error: function() {            alert("Error");        }    });}

此函数用于使用Ajax调用Http Handler。 要调用此函数,我们必须传递参数,如methodname,datatoinsert,callbackfunctionname,数据类型和数据。 如果它会成功执行,那么如果设置成功为true,它将转到成功函数,那么它将调用回调函数并将响应数据传递到json格式和消息中,但是如果发生任何错误,它将进入 错误功能。

接下来,添加保存按钮的客户端点击功能:

<input type="button" id="butSave" value="Save" onclick="SaveProducts()" />

并将以下函数SaveProducts添加到Commonfunction.js中,如下所示:

function SaveProducts() {    var Param = "name=" + document.getElementById("txtName").value +     "&unit=" + document.getElementById("txtUnit").value + "&Qty=" +     document.getElementById("txtQty").value;       if (ProductID == 0)        DoAjaxCall("?method=Insert&callbackmethod=InsertProductSucess", "script", Param);    else {        Param += "&ProductID=" + ProductID;        DoAjaxCall("?method=Update&callbackmethod=UpdateProductSucess", "script", Param);    }}

在这个函数中,我们必须将值传递给处理程序,将数据插入到数据库中,因此它将使用Querystring进行传递。之后,我们将检查用于确定用于将新记录输入到数据库中的当前点击的ProductID全局变量或数据库中的更新记录。所以如果ProductID的值为0,那么我们必须调用Insert方法,否则调用Update方法。

现在,对于插入,我们将参数作为method = Insert和callbackmethod = InserProductSucess和Parameter传递。现在这个函数调用了调用ProductList处理函数的DoAjaxCall全局函数,所以在Process Request方法的Handler中,我们将使用参数方法检查哪个方法调用。它将称之为相关参数方法。该方法执行其操作并将值分配给JsonResponse Call对象,最后,它将从该方法返回jsonresponse序列化对象。

该Json响应可用于Sucessfunction,从那里我们将检查该操作是否成功执行,然后它将调用该回调函数。

对于回调函数,我们必须在commonfunction.js的名称InsertProductSucess中添加一个函数,如下所示:

function InsertProductSucess(data, message) {    FillListing();    alert(message);    ClearValue();}function ClearValue() {    $("#txtName").val("");    $("#txtUnit").val("");    $("#txtQty").val("");}

这里,这种方法显示给用户的警告消息。 现在以相同的方式,以相同的方式添加其他操作的其他功能:

$(document).ready(function() { FillListing(); });function UpdateProductSucess(data, message) {    FillListing();    alert(message);    ProductID = 0;    ClearValue();}function FillListing() {    DoAjaxCall("?method=getproducts&callbackmethod=FillListingSucess", "script", "");}function FillListingSucess(data, message) {    var str = " &lt;table width="500px" cellspacing="0" cellpadding="2"     border="1">&lt;tbody>&lt;tr>&lt;td align="center" style="background-color: Gray;"     colspan="5">&lt;strong>Product Listing Page&lt;/strong>&lt;/td>&lt;/tr>&lt;tr>     &lt;td>Product Name&lt;/td>&lt;td>Unit&lt;/td>&lt;td>Qty&lt;/td>&lt;td>Delete&lt;/td>&lt;td>Edit&lt;/td>&lt;/tr>";    for (var i = 0; i &lt; data.length; i++) {        str += "&lt;tr>&lt;td>" + data[i].Name + "&lt;/td>";        str += "&lt;td>" + data[i].Unit + "&lt;/td>";        str += "&lt;td>" + data[i].Qty + "&lt;/td>";        str += "&lt;td>&lt;a onclick="DeleteProduct(" + data[i].ProductID + ")"         href="javascript:void(0)">Delete&lt;/a>&lt;/td>";        str += "&lt;td>&lt;a onclick="EditProduct(" + data[i].ProductID + ")"         href="javascript:void(0)">Edit&lt;/a>&lt;/td>&lt;/tr>";    }    str += "&lt;/tbody>&lt;/table>";    $('#ListingData').html(str);}function DeleteProduct(ProductID) {    DoAjaxCall("?method=delete&callbackmethod=DeleteSucess&param=" +         ProductID, "script", "");}function DeleteSucess(data, message) {    FillListing();    alert(message);}function EditProduct(ProductID) {    DoAjaxCall("?method=getbyid&callbackmethod=EditSucess&param=" +         ProductID, "script", "");}function EditSucess(data, message) {    ProductID = data.ProductID;    $("#txtName").val(data.Name);    $("#txtUnit").val(data.Unit);    $("#txtQty").val(data.Qty);}

现在尝试使用Default.aspx添加一个产品。 它会添加产品。 你会发现页面不会回发,lbltime不会显示更新的时间,或者你也可以查看Firebug。
这里写图片描述

结论

上面给出的例子是非常基本的。 您可以使用任何概念进行数据库操作,如Linq,Entity Framework等。本文包含示例源代码,您可以根据自己的需要自由修改。

本文引用:https://www.codeproject.com/Articles/283976/CRUD-Create-Read-Update-Delete

阅读全文
0 0
原创粉丝点击