Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Using the SqlDataSource Control LISTING 9.29 DynamicImage.ashx using using using using using System.Data; System.Web; System.Web.Configuration; System.Web.UI; System.Web.UI.WebControls; /// /// Displays an image corresponding to the Id passed /// in a query string field /// public class DynamicImage : IHttpHandler { public void ProcessRequest (HttpContext context) { // Get the Id of the image to display string imageId = context.Request.QueryString[“Id”]; // Use SqlDataSource to grab image bytes SqlDataSource src = new SqlDataSource(); src.ConnectionString = WebConfigurationManager.ConnectionStrings[“Images”].ConnectionString; src.SelectCommand = “SELECT Image FROM Images WHERE Id=” + imageId; // Return a DataView DataView view = (DataView)src.Select(DataSourceSelectArguments.Empty); context.Response.BinaryWrite( (byte[])view[0][“Image”]); // Return a DataReader. | 434 CHAPTER 9 Using the SqlDataSource Control LISTING 9.29 DynamicImage.ashx @ WebHandler Language C Class DynamicImage using System.Data using System.Web using System.Web.Configuration using System.Web.UI using System.Web.UI.WebControls summary Displays an image corresponding to the Id passed in a query string field summary public class Dynamicimage IHttpHandler public void ProcessRequest HttpContext context Get the Id of the image to display string imageId context.Request.QueryString Id Use SqlDataSource to grab image bytes SqlDataSource src new SqlDataSource src.ConnectionString WebConfigurationManager.ConnectionStrings Images .ConnectionString src.SelectCommand SELECT Image FROM Images WHERE Id imageId Return a DataView DataView view DataView src.Select DataSourceSelectArguments.Empty context.Response.BinaryWrite byte view 0 Image Return a DataReader src.DataSourceMode SqlDataSourceMode.DataReader IDataReader reader IDataReader src.Select DataSourceSelectArguments.Empty reader.Read context.Response.BinaryWrite byte reader Image reader.Close public bool IsReusable From the Library of Wow eBook Caching Database Data with the SqlDataSource Control 435 get return false In the ProcessRequest method an instance of the SqlDataSource control is created. The SqlDataSource control s Connectionstring and SelectCommand properties are initialized. Finally the SqlDataSource control s Select command is executed and the results are rendered with the Response.BinaryWrite method. The return value from the Select method is cast explicitly to a DataView object. You need to cast the return value to either a DataView or IDataReader for it to work with the results of the Select method. In Listing 9.29 the image bytes are returned in a DataView. To illustrate how you can use the Select method to return a DataReader I also included the code for returning the image with a DataReader but I added comments to the code so that it won t execute. Caching Database Data with the SqlDataSource .