在ASP.NET 2.0中操作数据之五十三:在Data Web控件显示二进制数
代码中的Response.ContentType属性指定了要返回内容的MIME type,以便浏览器知道如何显示数据。由于Categories表的Picture列存储的是位图图片,故在这里,位图图片的MIME type是(image/bmp). 如果你忽视了MIME type,绝大多数浏览器也可以正确的显示图像,因为,它们能根据图像文件的二进制数据的内容而推断其类型。即便如此,还是尽可能的使用MIME type。 创建页面后,可以访问页面 DisplayCategoryPicture.aspx?CategoryID=categoryID来查看某个特定类的图片。图11显示的是Beverages类的图片,页面为
有时候,当你访问DisplayCategoryPicture.aspx?CategoryID=categoryID页面时,有可能显示这样的提示:“Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'”。原因有可能是如下2方面。第一,表Categories的Picture列允许为NULL值,而DisplayCategoryPicture.aspx page页面总是假定传入的为非NULL值。当Picture为NULL值时,不能直接访问CategoriesDataTable的Picture属性。如果你允许Picture为NULL值,添加如下代码: if (category.IsPictureNull()) { // Display some "No Image Available" picture Response.Redirect("~/Images/NoPictureAvailable.gif"); } else { // Send back the binary contents of the Picture column // ... Set ContentType property and write out ... // ... data via Response.BinaryWrite ... } 上述代码假定在Images文件夹里存在名为NoPictureAvailable.gif的图片,当某个类没有图片时,就显示该图片。 另一种情况:当你在向导里选用“使用SQL语句”的模式再次运行主查询时,它将影响GetCategoryWithBinaryDataByCategoryID方法的SELECT命令返回的列(换句话说,主查询没有返回Picture列,再次运行主查询时将使GetCategoryWithBinaryDataByCategoryID方法也不会返回Picture列)。所以,应确保GetCategoryWithBinaryDataByCategoryID方法的SELECT命令返回Picture列。 注意:每次访问DisplayCategoryPicture.aspx页面时,都会访问数据库并返回所需的图片。如果图片自最近一次访问以来没有改变过的话,这样每次访问数据库再返回数据的做法效率是不高的。幸运的是,HTTP允许使用conditional GETs,这样的话,客户端使HTTP请求发送一个If-Modified-Since HTTP header。If-Modified-Since HTTP header包含了客户端最近一次从服务器获取的数据以及时间。如果请求的内容没有发生改变,服务器响应为Not Modified status code (304),并不返回请求的内容。简而言之,如果请求的资源自最近一次访问以来没发送改变的话,服务器将不会回传该资源,以达到减轻服务器负荷的目的。 第四步:在GridView控件里显示Category Pictures 现在我们有一个web页面来显示某个特定种类的图片的。通过Image Web控件或 HTML <img>元素来指向DisplayCategoryPicture.aspx?CategoryID=categoryID页面,从而达到显示该图片的目的。我们可以在GridView控件或DetailsView控件的 ImageField里显示图片。ImageField的DataImageUrlField属性、DataImageUrlFormatString属性与HyperLinkField的DataNavigateUrlFields属性、DataNavigateUrlFormatString属性用法相似。 让我们对DisplayOrDownloadData.aspx页面里名为Categories的GridView控件进行扩充。添加一个ImageField,设其DataImageUrlField属性为CategoryID;
添加完成后,你的GridView控件的声明代码看起来应像下面这样: <asp:GridView ID="Categories" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="CategoriesDataSource" EnableViewState="False"> <Columns> <asp:BoundField DataField="CategoryName" HeaderText="Category" SortExpression="CategoryName" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /> <asp:TemplateField HeaderText="Brochure"> <ItemTemplate> <%# GenerateBrochureLink(Eval("BrochurePath")) %> </ItemTemplate> </asp:TemplateField> <asp:ImageField DataImageUrlField="CategoryID" DataImageUrlFormatString="DisplayCategoryPicture.aspx?CategoryID={0}"> </asp:ImageField> </Columns> </asp:GridView> 花几分钟在浏览器里查看该页面,注意每一行记录现在都包含一张该类的图片。
总结: (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |