l 引言
本文一步步教你如何在Asp.net和Jquery Ajax API中用HttpHandler實現數據庫增改刪查的基本操作。為了簡單起見,本文不涉及表單驗證和應用程序界面設計方面的知識。
l 必備條件
在前面我提及已經通過Jquery Ajax API調用HttpHandler,因此需要在Web項目中添加jquery文件的引用,官方網址:http://jquery.com,如果使用vs2010開發,那么jquery文件默認包含在新建的Web項目中。
l 實現
首先在visual studio中新建Web項目,然后新建一個名為Script的文件夾,並添加一個名為Commonfunction.js空白js文件。
l 數據表設計
在Sqlserver數據庫中新建如下所示的Products數據表,並新建Products相關的數據操作類,代碼如下:

然后新建名為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; } } }
首頁Default.aspx中Product信息的相關html代碼如下,主要用來提交保存單條產品信息。

在頁面的head標簽中添加如下引用:
<script src="Script/jquery-1.2.6.js" type="text/javascript"></script> <script src="Script/CommonFunction.js" type="text/javascript"></script>
新建ProductList.ashx ,主要處理客戶端提交的ajax數據請求,代碼如下:

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<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中添加公用函數DoAjaxCall,該函數利用Ajax調用HttpHandler處理結果,並通過methodname, datatoinsert, callbackfunctionname, datatype 和 data等傳入的參數,來告知服務器端執行的操作(增改刪查)並返回服務器端處理成功或失敗的消息。

保存按鈕的客戶端事件SaveProducts()調用和定義如下,其中通過判斷ProductID是否為0來判斷當前的操作是插入還是更新產品信息。
<input type="button" id="butSave" value="Save" onclick="SaveProducts()" />

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); } }
l 結論
該例子講解數據庫操作的基本方法,當然也可用於Linq, Entity Framework等技術實現復雜的數據操作,點擊下載源碼,可按照自己的要求隨意修改它。
原文出處:http://www.codeproject.com/Articles/283976/CRUD-Create-Read-Update-Delete