接下来,让我们实现Product表的数据库操作类。
/// <summary> /// Product table data access manager. /// </summary> public class ProductManager { /// <summary> /// The query sql. /// </summary> private const string Query = "SELECT ProductID, Name, ProductNumber, SafetyStockLevel FROM Production.Product"; /// <summary> /// Stores the object of <see cref="ProductDao"/> into list. /// </summary> <ProductDao>(); /// <summary> /// Gets all products in product table. /// </summary> /// <returns> /// The list of <see cref="ProductDao"/> object. /// </returns> public IList<ProductDao> GetAllProducts() { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN"].ToString())) using (var com = new SqlCommand(Query, con)) { con.Open(); using (var reader = com.ExecuteReader(CommandBehavior.CloseConnection)) { while (reader.Read()) { var product = new ProductDao { Id = (int)reader["ProductID"], Name = (string)reader["Name"], SerialNumber = (string)reader["ProductNumber"], Qty = (short)reader["SafetyStockLevel"] }; _products.Add(product); } } } return _products; } }前面我们实现了Product表的数据库操作类——ProductManager,它包含两个私有字段Quey和_products,还有一个获取Product表中数据的方法——GetAllProducts()。
通过实现ProductDao和ProductManager,而且我们提供GetAllProducts()方法,获取Product表中的数据,接下来我们要调用该方法获取数据。
为了使数据通过JSON格式传递给页面,这里我们要创建一般处理程序(ASHX文件),
一般处理程序适用场合:
图1一般处理程序
把一般处理程序文件添加到项目中时,会添加一个扩展名为.ashx的文件,现在我们创建一个一般处理程序ProductInfo,具体代码如下:
%> using System.Runtime.Serialization.Json; using System.Web; using ASP.App_Code; /// <summary> /// The product data handler. /// </summary> public class ProductInfo : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "application/json"; // Creates a <see cref="ProductManager"/> oject. var manager = new ProductManager(); // Invokes the GetAllProducts method. var products = manager.GetAllProducts(); // Serializes data to json format. var json = new DataContractJsonSerializer(products.GetType()); json.WriteObject(context.Response.OutputStream, products); } // Whether can resuable by other handler or not. public bool IsReusable { get { return false; } } }大家注意到ProductInfo类实现了IHttpHandler接口,该接口包含一个方法ProcessRequest()方法和一个属性IsReusable。ProcessRequest()方法用于处理入站的Http请求。在默认情况下,ProductInfo类会把内容类型改为application/json,然后我们把数据通过JSON格式写入输入流中;IsReusable属性表示相同的处理程序是否可以用于多个请求,这里我们设置为false,如果为了提高性能也可以设置为true。
如下图所示,我们通过ProductInfo类成功地实现获取数据到响应流中,并且以JSON格式显示出来。
图2 Http请求
当我们请求ProductInfo时, 首先它会调用ProcessRequest()方法,接着调用GetAllProducts()方法从数据库中获取数据,然后把数据通过JSON格式写入到响应流中。
现在,我们已经成功地把数据通过JSON格式写入到响应流当中,接着我们将通过Ajax方式请求数据并且把数据显示到页面中。