65.9K
CodeProject 正在变化。 阅读更多。
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.82/5 (31投票s)

2011年11月15日

CPOL

3分钟阅读

viewsIcon

119248

downloadIcon

4768

在 ASP.NET 中实现 AJAX 的简单方法,无需使用 AJAX 控件

引言

本文将逐步演示如何使用 ASP.NET 中的 HttpHandler 和 Jquery Ajax API 创建 CRUD (Create, Read, Update, Delete) 操作的基本应用程序。 为了简化此应用程序,我没有涵盖验证以及良好设计的应用程序的其他方面。

要求

之前,我提到我使用了 Jquery Ajax API 来进行 HttpHandler 的 Ajax 调用,因此需要添加 Jquery 文件的引用。您可以从 https://jqueryjs.cn 获取最新的 Jquery 文件,或者如果您使用 VS2010,它将默认在 Web 项目中可用。

实现

CRUDOpeartionUsingJQuery/ProductUI.JPG

那么,第一步是创建一个新的 ASP.NET Web 项目。

然后创建一个名为 Script 的文件夹,并添加 Jquery 文件和一个空的 JavaScript 文件 Commonfunction.js

添加数据库

将 SqlServer 数据库文件添加到项目中,然后创建以下 Products

CRUDOpeartionUsingJQuery/DBScreenshot.JPG

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

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 标记添加到 head 标记中

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

接下来,添加名为 *ProductList.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<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。 要调用此函数,我们只需传递参数,如 methodnamedatatoinsertcallbackfunctionnamedatatypedata。 如果成功执行,它将进入成功函数,如果设置 success 为 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= Insertcallbackmethod=InserProductSucess 和参数传递。 现在,此函数调用 DoAjaxCall 全局函数,该函数调用 ProductList 处理程序,因此在处理程序中,在 Process Request 方法中,我们将检查使用参数方法调用了哪个方法。 它将调用该相关的参数方法。 该方法执行其操作并将一个值分配给 JsonResponse Call 对象,最后,它将从该方法返回 jsonresponse 序列化对象。

该 Json 响应在 Sucessfunction 中可用,并且从该响应中,我们只需检查该操作是否成功执行,然后它将调用该回调函数。

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

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

在此,此方法向用户显示该 alert 消息。 现在,以相同的方式为其他操作添加其他函数。

$(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 = " <table width="500px" cellspacing="0" cellpadding="2" 
    border="1"><tbody><tr><td align="center" style="background-color: Gray;" 
    colspan="5"><strong>Product Listing Page</strong></td></tr><tr> 
    <td>Product Name</td><td>Unit</td><td>Qty</td><td>Delete</td><td>Edit</td></tr>";

    for (var i = 0; i < data.length; i++) {
        str += "<tr><td>" + data[i].Name + "</td>";
        str += "<td>" + data[i].Unit + "</td>";
        str += "<td>" + data[i].Qty + "</td>";
        str += "<td><a onclick="DeleteProduct(" + data[i].ProductID + ")" 
        href="javascript:void(0)">Delete</a></td>";
        str += "<td><a onclick="EditProduct(" + data[i].ProductID + ")" 
        href="javascript:void(0)">Edit</a></td></tr>";
    }
    str += "</tbody></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* 添加一个 Product。 它将添加产品。 您会发现该页面不会回发,并且 lbltime 不会显示更新的时间,或者您也可以在 Firebug 中检查。

FireBug.JPG - Click to enlarge image

结论

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

历史

  • 2011年11月15日:初始发布
© . All rights reserved.