当前位置: 移动技术网 > IT编程>开发语言>.net > 在ASP.NET 2.0中操作数据之五十五:编辑和删除现有的二进制数据

在ASP.NET 2.0中操作数据之五十五:编辑和删除现有的二进制数据

2017年12月12日  | 移动技术网IT编程  | 我要评论

3773考试网,2012f1马来西亚,孔晴逸

导言:

  在前面的3章里我们为处理二进制数据添加了很多的功能。我们首先在表categories里添加brochurepath列,并更新了体系结构。同样,为了处理表categorie里现有的picture列,我们在数据访问层和业务逻辑层里增加了相应的方法。同时我们创建一个页面,在gridview控件里显示二进制数据——包含一个指向说明小册子的下载链接,并将每个类的图片显示在<img>元素里。同时我们添加一个detailsview控件,供用户添加新的类,并上传其图片和小册子数据。

  剩下的就是添加编辑和删除功能,本章我们将通过gridview控件内建的编辑和删除功能来实现。当编辑一个类时,我们允许用户用任意指定的图片将原来的换掉;也可以用新的小册子将现有的替换掉,甚至不再包含小册子文件。让我们开始吧!

第1步:更新数据访问层

  虽然数据访问层包含自动生成的insert, update和delete方法,但它们都基于categoriestableadapter的主查询,因此并不包含picture列。自然,insert和update方法也不包含picture列的相应参数。就像56章做的那样,我们需要为更新categories表而创建新的tableadapter方法。

  右键点击categoriestableadapter的顶部,选择“添加查询”,打开tableadapter查询设置向导,我们首先选择“使用sql语句”,点next,再选“update”,再点next.

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908311471.jpg
图1:选择“update”选项

我们现在需要指定update sql语句。向导自动创建一个基于tableadapter主查询的update语句(它更新categoryname, description和brochurepath值)。更新该语句以包含picture列,以及@picture参数,像如下这样:

update [categories] set
 [categoryname] = @categoryname,
 [description] = @description,
 [brochurepath] = @brochurepath ,
 [picture] = @picture
where (([categoryid] = @original_categoryid))

最后,向导要求我们为新的tableadapter方法命名,我们取为updatewithpicture,再点finish。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908313541.jpg
图2:为新方法命名为updatewithpicture

第2步:添加新的业务逻辑方法

除了更新dal外,我们需要更新bll以包含更新、删除类的方法。以下是表现层需要调用的方法:

为了删除一个类,我们使用categoriestableadapter的自动生成的delete方法,在类categoriesbll里添加如下的方法:

[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.delete, true)]
public bool deletecategory(int categoryid)
{
 int rowsaffected = adapter.delete(categoryid);

 // return true if precisely one row was deleted, otherwise false
 return rowsaffected == 1;
}

  本教程,为了更新一个类,我们将创建2个方法。一个方法接受picture值,并调用我们刚刚添加到categoriestableadapter里的updatewithpicture方法。另一个方法只接受categoryname, description和brochurepath值, 并调用categoriestableadapter类里自动生成的update语句。为什么要使用2种方法呢?某些情况下,用户更新类时同时更新其图片,这时就需要上传一张新图片。上传图片的数据将在update语句里用到;另一种情况,用户只想更新类的name和description信息,因此我们需要使用2种更新方法。业务逻辑层会根据是否传入picture值来判断使用哪种方法。

  为达该目的,我们要在categoriesbll类里添加2个方法,名字都是updatecategory,第一个方法接受的参数包括3个string,1个byte数组和1个int;第二个方法接受的参数包括3个string和1个int。3个字符串参数代表类的name, description和brochure文件路径,byte数组包含的是类的picture数据,int代表类记录的categoryid,我们注意到,当传入的byte数组为null时,第一个方法将调用第二个方法。

[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.update, false)]
public bool updatecategory(string categoryname, string description,
 string brochurepath, byte[] picture, int categoryid)
{
 // if no picture is specified, use other overload
 if (picture == null)
 return updatecategory(categoryname, description, brochurepath, categoryid);

 // update picture, as well
 int rowsaffected = adapter.updatewithpicture
 (categoryname, description, brochurepath, picture, categoryid);

 // return true if precisely one row was updated, otherwise false
 return rowsaffected == 1;
}

[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.update, true)]
public bool updatecategory(string categoryname, string description,
 string brochurepath, int categoryid)
{
 int rowsaffected = adapter.update
 (categoryname, description, brochurepath, categoryid);

 // return true if precisely one row was updated, otherwise false
 return rowsaffected == 1;
}

第3步:拷贝功能

  在上一章里,我们创建了一个uploadindetailsview.aspx页面,在一个gridview控件列出所有的类,再通过一个detailsview控件来添加新的类。在本教程,我们将扩展gridview控件以支持编辑和删除功能。不过我们不再使用uploadindetailsview.aspx页面,让我们在~/binarydata文件夹里创建一个新页面,updatinganddeleting.aspx,将uploadindetailsview.aspx页面的声明代码复制并粘贴到页面updatinganddeleting.aspx.

  打开uploadindetailsview.aspx页面,将其<asp:content>元素里的声明代码复制下来,就像图3那样。接下来,打开updatinganddeleting.aspx页面,把代码粘贴在<asp:content>元素里。同样的,将uploadindetailsview.aspx页面的后台代码拷贝到updatinganddeleting.aspx。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908311313.jpg
图3:将uploadindetailsview.aspx页面的声明代码拷贝下来

完成后,登录updatinganddeleting.aspx页面,你将会看到相同的输出效果。感觉用起来和uploadindetailsview.aspx页面一样。

第4步:添加objectdatasource和gridview的删除功能

  就像在教程16《》里探讨的一样,只要gridview控件绑定的数据源支持“删除”功能,我们就可以为gridview控件启用删除功能。不过,gridview控件绑定的objectdatasource(也就是categoriesdatasource)目前并不支持删除。

  为支持删除,在objectdatasource的智能标签里点“配置数据源”,一直点到“定义数据方法”界面。虽然当前只指定了objectdatasource控件insertmethod属性和selectmethod属性,但向导自动地分别为update标签和delete标签指定updatecategory方法和deletecategory方法。为什么呢?因为我们在categoriesbll类里为上述2种方法使用了dataobjectmethodattribute属性,作用是分别使其成为默认的“更新”和“删除”方法。

  不过现在我们在update标签的下拉列表里选“(none)”, 而 delete标签里仍然为deletecategory方法。我们将在第6步添加更新功能。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908313384.jpg
图4:设置objectdatasource控件使用deletecategory方法

  注意:完成设置后,visual studio会问你是否“刷新列和主键”,选择no,因为选择yes将会把我们自己定制的任何列覆盖掉。

  现在,objectdatasource控件将包含deletemethod属性和对应的deleteparameter参数。我们记得在以前的教程提到过,当使用向导指定方法时,visual studio会自动的将objectdatasource控件的oldvaluesparameterformatstring属性设置为original_{0},这将导致更新和删除时出现问题。为此,要么将清除该属性,要么将其设置为默认的{0}值。对该属性的更详细讨论见教程16《》

完成后,objectdatasource控件的声明代码看起来应该像下面的一样:

<asp:objectdatasource id="categoriesdatasource" runat="server"
 oldvaluesparameterformatstring="{0}" selectmethod="getcategories"
 typename="categoriesbll" insertmethod="insertwithpicture"
 deletemethod="deletecategory">
 <insertparameters>
 <asp:parameter name="categoryname" type="string" />
 <asp:parameter name="description" type="string" />
 <asp:parameter name="brochurepath" type="string" />
 <asp:parameter name="picture" type="object" />
 </insertparameters>
 <deleteparameters>
 <asp:parameter name="categoryid" type="int32" />
 </deleteparameters>
</asp:objectdatasource>

设置完objectdatasource后,就可以启用gridview的删除功能了,方法是点击其智能标签里的“删除选项”。这将使gridview增加一个commandfield,其showdeletebutton属性为true。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908321156.jpg
图5:启用gridview控件的删除功能

  花几分钟测试删除功能。由于表products和表categories之间有一个外键categoryid,当你删除现有的8个类中的任何一个时,你会得到一个外键约束冲突异常。为顺利的实现测试,我们需要添加一个附带图片和说明小册子的新类,如图6所示,小册子为test.pdf,图7为添加了测试类的gridview控件界面。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908326455.jpg
图6:添加一个附带brochure和image文件的测试类

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908324228.jpg
图7:添加测试类后,显示在gridview控件里

在visual studio里刷新解决资源管理器,你会在文件夹~/brochures里看到test.pdf文件(见图8)

下一步,点击test类的delete链接,页面回传,引发categoriesbll的deletecategory 方法,该方法又调用dal层的delete方法,向数据库发送适当的delete命令。最后数据重新绑定到gridview控件,test类将不再显示出来。

虽然已经成功地将test类从categories表删除,但存储在文件系统的对应小册子仍旧存在,刷新解决资源管理器,你将发现test.pdf依然放在~/brochures文件夹里。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908325513.jpg
图8:test.pdf文件并没有从文件系统删除

第5步:删除残存的brochure文件

  未将二进制数据存储进数据库时面临的一个问题便是:当删除一条数据库记录时,我们需要另外采取步骤来删除该记录对应的二进制数据文件。当执行delete命令时,会发生一些事前事件和事后事件(pre- and post-action events),我们需要创建对应的事件处理器。在categories表的记录被删除之前,我们需要确定对应pdf文件的路径,但在删除记录之前我们不会删除其对应的pdf文件,以防发生异常或记录最终未被删除的情况。

  从事件发生的时间先后顺序来看,gridview控件的rowdeleting事件在调用objectdatasource控件的delete命令前发生;而rowdeleted事件在调用objectdatasource控件的delete命令之后再发生。创建这2个事件处理器,代码如下:

// a page variable to "remember" the deleted category's brochurepath value
string deletedcategoryspdfpath = null;

protected void categories_rowdeleting(object sender, gridviewdeleteeventargs e)
{
 // determine the pdf path for the category being deleted...
 int categoryid = convert.toint32(e.keys["categoryid"]);

 categoriesbll categoryapi = new categoriesbll();
 northwind.categoriesdatatable categories =
 categoryapi.getcategorybycategoryid(categoryid);
 northwind.categoriesrow category = categories[0];

 if (category.isbrochurepathnull())
 deletedcategoryspdfpath = null;
 else
 deletedcategoryspdfpath = category.brochurepath;
}

protected void categories_rowdeleted(object sender, gridviewdeletedeventargs e)
{
 // delete the brochure file if there were no problems deleting the record
 if (e.exception == null)
 {
 // is there a file to delete?
 if (deletedcategoryspdfpath != null)
 {
  system.io.file.delete(server.mappath(deletedcategoryspdfpath));
 }
 }
}

  在rowdeleting事件处理器里,从gridview控件的datakeys集合里获取被删记录的categoryid值,而在这里,我们通过e.keys来访问datakeys集合。接着,调用类categoriesbll的getcategorybycategoryid(categoryid)方法来返回被删记录的信息,若返回的brochurepath值不为null,那么将其赋值给页面参数deletedcategoryspdfpath,再在rowdeleted事件处理器里删除文件。

  注意:在rowdeleting事件处理器里,我们没有返回被删记录的brochurepath信息,而是将brochurepath添加到gridview的datakeynames属性,再通过访问e.keys来获取该记录的值。这样做虽然稍微增大了gridview的视图状态,但减少了必要的代码,也省了一步访问数据库。

  调用objectdatasource控件的delete命令后,紧接着发生gridview控件的rowdeleted事件,如果删除过程没有异常且deletedcategoryspdfpath值不为空,那就将对应的pdf文件从文件系统删除。我们注意到,代码没有删除类的picture,那是因为picture数据是直接存储在数据库里的,当删除记录时就一起删除了。

  添加完上述2个事件处理器后,再次测试删除。当删除某个类时,其对应的pdf文件也删除了。

  下面我们深入研究添加更新功能以应对类的brochure和picture.第6步探讨更新brochure信息的技术,第7章探讨更新picture。

第6步:更新类的brochure

  就像在教程16《》里探讨的一样,如果gridview的数据源控件支持编辑,那么我们就可以启用gridview控件的编辑功能。当前,名为categoriesdatasource的objectdatasource控件并不支持编辑,那让我们添加吧。

  点击objectdatasource控件的“设置数据源”链接,一直点到“定义数据方法”界面。由于在categoriesbll里对重载的updatecategory方法使用了dataobjectmethodattribute属性,update标签的下拉列表自动的选择了该方法,它包含4个输入参数(不包含picture)。我们选择另一个包含5个输入参数的重载的updatecategory方法。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908329056.jpg
图9:设置objectdatasource控件使用包含picture参数的updatecategory方法

  objectdatasource控件现在包含了updatemethod属性以及相应的updateparameters参数集。就像在第4步提到的一样,当使用设置向导时,visual studio会将objectdatasource控件的oldvaluesparameterformatstring属性设置为original_{0},这导致调用update和delete方法时出现问题。因此,要么将该属性清除,要么设该属性为{0}。

完成后,objectdatasource控件的声明代码看起来应该和下面的差不多:

<asp:objectdatasource id="categoriesdatasource" runat="server"
 oldvaluesparameterformatstring="{0}" selectmethod="getcategories"
 typename="categoriesbll" insertmethod="insertwithpicture"
 deletemethod="deletecategory" updatemethod="updatecategory">
 <insertparameters>
 <asp:parameter name="categoryname" type="string" />
 <asp:parameter name="description" type="string" />
 <asp:parameter name="brochurepath" type="string" />
 <asp:parameter name="picture" type="object" />
 </insertparameters>
 <deleteparameters>
 <asp:parameter name="categoryid" type="int32" />
 </deleteparameters>
 <updateparameters>
 <asp:parameter name="categoryname" type="string" />
 <asp:parameter name="description" type="string" />
 <asp:parameter name="brochurepath" type="string" />
 <asp:parameter name="picture" type="object" />
 <asp:parameter name="categoryid" type="int32" />
 </updateparameters>
</asp:objectdatasource>

要启用编辑功能,从gridview控件的智能标签里选“编辑”。这将设置commandfield的showeditbutton属性为true,结果是为每行添加一个edit按钮(当记录处于编辑状态时,将呈现为update和cancel按钮)

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908336829.jpg
图10:启用gridview控件的编辑功能

  从浏览器查看该页面,点某条记录的edit按钮。categoryname和description列呈现为一个文本框。由于brochurepath templatefield没有edititemtemplate模板,所以它依旧呈现其itemtemplate模板——一个指向brochure的链接。picture列呈现为一个文本框,并且该picture imagefield的text属性被指派为dataimageurlfield值,在这里,即categoryid.

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908333129.jpg
图11:brochurepath列没有编辑界面

定制brochurepath编辑界面

我们可以为brochurepath templatefield创建一个编辑界面,我们可以选择:

.维持原样
.上传新的brochure以作更新
.将brochure删除(这样一来,类就没有对应的brochure了)

我们也应该更新picture imagefield的编辑界面,不过我们将放在第7步来讨论。

  在gridview控件的智能标签里选择“编辑模板”,再从下拉列表里选brochurepath templatefield的edititemtemplate模板。在模板里添加一个radiobuttonlist web控件,其id为brochureoptions;autopostback属性为true.再在属性窗口里点items属性的椭圆型区域,进入listitem collection editor界面,分别添加值为1,2,3的选项:

.use current brochure
.remove current brochure
.upload new brochure

设第一个listitem的selected属性为true.

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908331185.jpg
图12:为radiobuttonlist控件添加3个listitems

在radiobuttonlist控件下面,添加一个fileupload控件,id为brochureupload,设其visible属性为false。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908342814.jpg
图13:在edititemtemplate模板里添加radiobuttonlist和fileupload控件

radiobuttonlist控件为用户提供了3个选择,只有当选择“upload new brochure”时, fileupload控件才会展现出来。为此,我们为radiobuttonlist控件的selectedindexchanged事件创建事件处理器,如下:

protected void brochureoptions_selectedindexchanged(object sender, eventargs e)
{
 // get a reference to the radiobuttonlist and its parent
 radiobuttonlist brochureoptions = (radiobuttonlist)sender;
 control parent = brochureoptions.parent;

 // now use findcontrol("controlid") to get a reference of the
 // fileupload control
 fileupload brochureupload =
 (fileupload)parent.findcontrol("brochureupload");

 // only show brochureupload if selectedvalue = "3"
 brochureupload.visible = (brochureoptions.selectedvalue == "3");
}

  由于radiobuttonlist控件和fileupload控件同时出现在一个模板里,我们需要通过编程来访问这2个控件。在selectedindexchanged事件处理器里,我们通过输入参数sender来引用radiobuttonlist控件。为了获取fileupload控件,我们需要使用radiobuttonlist的父控件(parent control),并使用findcontrol("controlid")方法。一旦我们同时获取了radiobuttonlist和fileupload控件时,只要radiobuttonlist控件的selectedvalue值等于3,即“upload new brochure” listitem的值时,将fileupload控件的visible属性设置为true 。

  添加完上述代码后,花几分钟时间来测试编辑页面。点击某行的edit按钮,默认是选中“use current brochure”项,改选另一项,页面产生回传,如果是选择第3项,则fileupload控件将会显示出来,否则处于隐身状态。图14显示点击edit按钮的情形,而图15则是选择“upload new brochure”时的情形。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908348801.jpg
图14:默认选择“use current brochure”项

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908348614.jpg
图15:选择“upload new brochure”时fileupload控件显示出来

保存brochure文件并更新brochurepath列

当点击gridview控件的update按钮时,触发rowupdating事件,调用objectdatasource控件的update命令,然后触发gridview控件的rowupdated事件。跟deleting流程类似,我们需要创建这些事件的处理器。在rowupdating事件处理器里,我们需要根据radiobuttonlist的selectedvalue值来判断下一步怎么做。

.如果selectedvalue值为1,我们将保持rochurepath不变。所以我们将objectdatasource控件的brochurepath参数设置为当前处于编辑状态记录的brochurepath值,方法为e.newvalues["brochurepath"] = value.

.如果selectedvalue值为2,意味着将brochurepath设为null。为此,我们需要将objectdatasource控件的brochurepath参数设为nothing,结果就是在update命令里使用null。如果存在对应的brochure文件,我们必须将其删除,前提是没有抛出任何的异常。

.如果selectedvalue值为3,我们必须确保用户已经上传了一个pdf文件并将其保存在文件系统,然后更新记录的brochurepath值。我们要先将被替换的前一个文件删除掉,当然前提是没有引发异常。

在上一章里,当在detailsview控件里添加新记录时,触发detailsview控件的iteminserting事件。在本章,当radiobuttonlist控件的selectedvalue为3时(即我们选择upload new brochure时),接下来要采取的步骤实际上与detailsview控件的iteminserting事件处理器实现的功能相似。根据实现的功能,我划分为2个方法:

.processbrochureupload(fileupload, out bool):它以一个fileupload控件实例为输入参数,结果为一个布尔值(boolean)。根据该布尔值判断是否继续更新或删除操作,抑或取消操作。如果存在上传文件该方法就返回其路径,反之返回null。

.deleterememberedbrochurepath:如果页面变量deletedcategoryspdfpath不为null,则删除该参数指定的文件。

下面是上述2种方法的代码。注意processbrochureupload方法和detailsview控件的iteminserting事件处理器有某些相似性,在本章,我们更新detailsview控件的事件处理器以使用这些新方法。下载本章的代码,查看我们对detailsview控件的事件处理器所做的修改。

private string processbrochureupload
 (fileupload brochureupload, out bool canceloperation)
{
 canceloperation = false; // by default, do not cancel operation

 if (brochureupload.hasfile)
 {
 // make sure that a pdf has been uploaded
 if (string.compare(system.io.path.getextension(brochureupload.filename),
  ".pdf", true) != 0)
 {
  uploadwarning.text =
  "only pdf documents may be used for a category's brochure.";
  uploadwarning.visible = true;
  canceloperation = true;
  return null;
 }

 const string brochuredirectory = "~/brochures/";
 string brochurepath = brochuredirectory + brochureupload.filename;
 string filenamewithoutextension =
  system.io.path.getfilenamewithoutextension(brochureupload.filename);

 int iteration = 1;

 while (system.io.file.exists(server.mappath(brochurepath)))
 {
  brochurepath = string.concat(brochuredirectory, filenamewithoutextension,
  "-", iteration, ".pdf");
  iteration++;
 }

 // save the file to disk and set the value of the brochurepath parameter
 brochureupload.saveas(server.mappath(brochurepath));
 return brochurepath;
 }
 else
 {
 // no file uploaded
 return null;
 }
}

private void deleterememberedbrochurepath()
{
 // is there a file to delete?
 if (deletedcategoryspdfpath != null)
 {
 system.io.file.delete(server.mappath(deletedcategoryspdfpath));
 }
}

在gridview控件的rowupdating和rowupdated事件处理器里使用上面2个方法,如下:

protected void categories_rowupdating(object sender, gridviewupdateeventargs e)
{
 // reference the radiobuttonlist
 radiobuttonlist brochureoptions =
 (radiobuttonlist)categories.rows[e.rowindex].findcontrol("brochureoptions");

 // get brochurepath information about the record being updated
 int categoryid = convert.toint32(e.keys["categoryid"]);

 categoriesbll categoryapi = new categoriesbll();
 northwind.categoriesdatatable categories =
 categoryapi.getcategorybycategoryid(categoryid);
 northwind.categoriesrow category = categories[0];

 if (brochureoptions.selectedvalue == "1")
 {
 // use current value for brochurepath
 if (category.isbrochurepathnull())
  e.newvalues["brochurepath"] = null;
 else
  e.newvalues["brochurepath"] = category.brochurepath;
 }
 else if (brochureoptions.selectedvalue == "2")
 {
 // remove the current brochure (set it to null in the database)
 e.newvalues["brochurepath"] = null;
 }
 else if (brochureoptions.selectedvalue == "3")
 {
 // reference the brochurepath fileupload control
 fileupload brochureupload =
  (fileupload)categories.rows[e.rowindex].findcontrol("brochureupload");

 // process the brochureupload
 bool canceloperation = false;
 e.newvalues["brochurepath"] =
  processbrochureupload(brochureupload, out canceloperation);

 e.cancel = canceloperation;
 }
 else
 {
 // unknown value!
 throw new applicationexception(
  string.format("invalid brochureoptions value, {0}",
  brochureoptions.selectedvalue));
 }

 if (brochureoptions.selectedvalue == "2" ||
 brochureoptions.selectedvalue == "3")
 {
 // "remember" that we need to delete the old pdf file
 if (category.isbrochurepathnull())
  deletedcategoryspdfpath = null;
 else
  deletedcategoryspdfpath = category.brochurepath;
 }
}

protected void categories_rowupdated(object sender, gridviewupdatedeventargs e)
{
 // if there were no problems and we updated the pdf file,
 // then delete the existing one
 if (e.exception == null)
 {
 deleterememberedbrochurepath();
 }
}

注意:rowupdating事件处理器是如何根据selectedvalue值的不同而使用一系列的条件语句来实现相应的功能。

使用上面的代码,我们就可以编辑一个类了,使用其当前的brochure,或不使用brochure,再或者使用一个新的brochure。在rowupdating和rowupdated事件处理器里设置断点(breakpoints)吧,以便更好的理解处理流程。

第7步:上传新图片

  picture imagefield的编辑界面呈现为一个文本框,里面显示的是dataimageurlfield 属性的值。在编辑流程,gridview控件向objectdatasource传入一个参数,参数名为imagefield的dataimageurlfield属性;参数值为在编辑界面输入文本框里的值。当图片是存储在文件系统,且dataimageurlfield属性包含的是访问该图片的完整url时,这样做是恰当的。在这种情况下,在编辑界面里,文本框将会显示图片的url。毫无疑问,默认的界面不允许用户上传新的图片,但用户却可以修改图片的url值。不过,在本教程不会出现这种情况,因为picture数据是直接存储在数据库的,且dataimageurlfield属性被设为categoryid值。

  为了更好的理解在本教程里编辑某行的imagefield时将会发生上什么,我们做如下假设:用户编辑一个categoryid值为10行,picture imagefield呈现为一个文本框,显示10,假设用户将其改为50后点update按钮,页面回传,gridview控件最初产生一个名为categoryid,值为50的参数。在gridview传递此参数(连同参数categoryname和参数description一起)以前,对datakeys集添加值。因此,将当前行的categoryid值10,覆盖掉。简言之,imagefield的编辑界面没有对本章教程的编辑流程产生任何影响,因为imagefield的dataimageurlfield属性和datakey值都是同一个值。

  当图片存储在数据库时,imagefield将其显示出来也很容易。不过在编辑界面里我们不需要使用文本框,而提供一个fileupload控件供最终用户更改图片时使用。与brochurepath不同,我们不允许类的图片为空——用户要么提供新图片要么使用当前的图片。

  为定制imagefield的编辑界面,我们需要将其转化为一个templatefield。在gridview控件的智能标签里点击“编辑列”,进入后选中imagefield,再点击“convert this field into a templatefield”链接。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908342373.jpg
图16:将imagefield转换为templatefield

  转换后的templatefield由2个模版构成。就像下面的声明代码显示的那样,itemtemplate模版包含一个image web控件,其imageurl属性由一个数据绑定语法指定,该数据绑定语法基于imagefield的dataimageurlfield和 dataimageurlformatstring属性。而edititemtemplate模版则包含一个textbox,其text属性绑定到dataimageurlfield属性的值。

<asp:templatefield>
 <edititemtemplate>
 <asp:textbox id="textbox1" runat="server"
  text='<%# eval("categoryid") %>'></asp:textbox>
 </edititemtemplate>
 <itemtemplate>
 <asp:image id="image1" runat="server"
  imageurl='<%# eval("categoryid",
  "displaycategorypicture.aspx?categoryid={0}") %>' />
 </itemtemplate>
</asp:templatefield>

  我们需要更新edititemtemplate模版以包含一个fileupload控件。从gridview控件的智能标签点“编辑模版”,再在下拉列表选择picture templatefield的edititemtemplate模版。在模版里你会看见一个textbox,将其删除。从工具箱里拖一个fileupload控件到页面,设其id为pictureupload。同时在模版里添加如下的文本:“to change the category's picture, specify a new picture. to keep the category's picture the same, leave the field empty”。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908354443.jpg
图17:在edititemtemplate模版里添加一个fileupload控件


完成定制该编辑界面后,在浏览器里查看。在只读模式里,类的图片和以前没什么两样,当点击edit按钮时,picture列将呈现一段文本和一个fileupload控件。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908357201.jpg
图18:编辑界面包含一个fileupload控件

  记得我们设置objectdatasource控件调用categoriesbll的updatecategory方法,该方法的一个输入参数为数组,用于处理图片的数据。如果该数组为null值,则调用另一个重载的updatecategory方法,该重载的updatecategory方法的update sql语句不会更改picture列,因此类的图片不会由任何变化。在gridview控件的rowupdating事件处理器里,我们编程访问名为pictureupload的fileupload控件,判断是否上传了文件。如果没有文件上传,我们将不会为参数picture指定值;反之,如果上传了文件,我们将确保其为jpg格式的文件,并通过参数picture将其传给objectdatasource控件。

  就像第6步里的代码一样,我们此时将要用到的绝大多数的代码已经存在于detailsview控件的iteminserting事件处理器里了。现在我们创建一个新的方法validpictureupload,并更新iteminserting事件处理器以使用该方法。

  在gridview控件的rowupdating事件处理器的开头部分添加如下的代码,这很重要,因为我们不希望将一个不符合条件的上传文件存储在文件系统。

// reference the pictureupload fileupload
fileupload pictureupload =
 (fileupload)categories.rows[e.rowindex].findcontrol("pictureupload");
if (pictureupload.hasfile)
{
 // make sure the picture upload is valid
 if (validpictureupload(pictureupload))
 {
 e.newvalues["picture"] = pictureupload.filebytes;
 }
 else
 {
 // invalid file upload, cancel update and exit event handler
 e.cancel = true;
 return;
 }
}

  validpictureupload(fileupload)方法只有一个fileupload控件类型的输入参数,通过检查上传文件的扩展符以确保上传的文件为jpg格式。只有当上传了文件时才会调用该方法;如果没有文件上传,参数picture就只能使用其默认值—null。如果上传了图片,且validpictureupload方法返回值true,将用图片的二进制数据对参数picture赋值。如果validpictureupload方法返回值false,则取消更新,并退出事件处理器。

validpictureupload(fileupload)方法的代码如下:

private bool validpictureupload(fileupload pictureupload)
{
 // make sure that a jpg has been uploaded
 if (string.compare(system.io.path.getextension(pictureupload.filename),
  ".jpg", true) != 0 &&
 string.compare(system.io.path.getextension(pictureupload.filename),
  ".jpeg", true) != 0)
 {
 uploadwarning.text =
  "only jpg documents may be used for a category's picture.";
 uploadwarning.visible = true;
 return false;
 }
 else
 {
 return true;
 }
}

第8步:将原始几个类的图片替换为jpg格式

回想起最开始的那8个类的图片为位图文件其包含一个ole报头。现在我们添加了新功能以编辑现有记录的图片,花几分钟将这些位图文件替换为jpg文件。如果你想使当前类的图片不变,你可以通过下面的布置将其转换为jpg格式:

1.将这些位图保存在硬盘。在浏览器里访问updatinganddeleting.aspx页面,对这8个类的图片,点右键,选则保存图片。

2.在一个图片编辑器(比如microsoft paint)软件里打开图片。

3.将图片保存为jpg格式

4.在编辑界面里,用jpg图片更新类的picture

完成更新并上传jpg图片之后,图片不会呈现在浏览器里,原因是displaycategorypicture.aspx将尝试对最开始8个类的图片剥离ole报头。怎样修正呢?我们将剥离ole报头的代码移除。这样,displaycategorypicture.aspx页面的page_load事件处理器的代码如下:

protected void page_load(object sender, eventargs e)
{
 int categoryid = convert.toint32(request.querystring["categoryid"]);

 // get information about the specified category
 categoriesbll categoryapi = new categoriesbll();
 northwind.categoriesdatatable categories = _
 categoryapi.getcategorywithbinarydatabycategoryid(categoryid);
 northwind.categoriesrow category = categories[0];

 // for new categories, images are jpgs...
 
 // output http headers providing information about the binary data
 response.contenttype = "image/jpeg";

 // output the binary data
 response.binarywrite(category.picture);
}

注意:updatinganddeleting.aspx页面的编辑和添加界面要稍微复杂一点。detailsview和gridview控件里的categoryname和description  boundfields应当转换成templatefields;另外由于categoryname不能为null值,应对其添加一个requiredfieldvalidator控件。此外,description应修改为允许换行的的文本框(multi-line textbox),我将这些留给读者作为练习。

总结:
  本篇为处理二进制数据的完结篇,在本章以及前3章我们考察了如何将二进制数据存放在文件系统或直接存储在数据库里。用户在硬盘里选择一个文件并将其上传到服务器,再存放在文件系统或数据库。asp.net 2.0的fileupload控件提供了上传的界面。然而,就像在教程《使用fileupload上传文件》里提到的那样,fileupload控件控件只适合于上传小于1mb的文件。我们也探讨了如何编辑和删除当前记录的二进制数据。

在接下来的一系列教程里,我们探讨各种缓存技术。使用缓存可以提升应用程序的整体性能。

  祝编程快乐!

作者简介

  本系列教程作者 scott mitchell,著有六本asp/asp.net方面的书,是4guysfromrolla.com的创始人,自1998年以来一直应用 微软web技术。大家可以点击查看全部教程《[翻译]scott mitchell 的asp.net 2.0数据教程》,希望对大家的学习asp.net有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网