在ASP.NET 2.0中怎么处理BLL和DAL异常
创始人
2024-11-28 13:23:05
0次

第一步: 创建一个可编辑的DataList

  首先创建一个可编辑的DataList。打开EditDeleteDataList文件夹下的ErrorHandling.aspx页,添加一个ID为Products的DataList和一个名为ProductsDataSource的ObjectDataSouce。在SELECT标签下选择ProductsBLL类的GetProducts()方法。在INSERT,UPDATE和DELETE标签里选择None.

在ASP.NET 2.0中怎么处理BLL和DAL异常
图 1: 配置ObjectDataSource

  完成ObjectDataSouce后,Visual Studio会自动创建一个ItemTemplate。用显示每个product的name和price并包含一个Edit button的ItemTemplate代替它,然后创建一个用TextBox显示name和price,并包含一个Update button和Cancel button的EditItemTemplate。最后将DataList的RepeatColumns属性设为2。

  做完这些后,你的声明代码应该和下面的差不多。检查并确保Edit,Cancel和Update button的CommandName属性,分别被设为“Edit”, “Cancel”, 和“Update”。


 
  
   ' />   
  Price:    ' />               
    Product name:    ' />      Price:    ' />                 

  注意:本章里DataList的view state必须开启。浏览一下页面,见图2。

在ASP.NET 2.0中怎么处理BLL和DAL异常
图 2: 每个Product 都包含一个Edit Button

  现在Edit button只是引起一个postback —还不能将product变成可编辑的。为了实现编辑功能,我们需要为EditCommand,CancelCommand和UpdateCommand创建事件处理。EditCommand和CancelCommand事件仅仅只需要更新DataList的EditItemIndex属性,并重新绑定数据到DataList。

protected void Products_EditCommand(object source, DataListCommandEventArgs e)
{
 // Set the DataList's EditItemIndex property to the
 // index of the DataListItem that was clicked
 Products.EditItemIndex = e.Item.ItemIndex;
 // Rebind the data to the DataList
 Products.DataBind();
}
protected void Products_CancelCommand(object source, DataListCommandEventArgs e)
{
 // Set the DataList's EditItemIndex property to -1
 Products.EditItemIndex = -1;
 // Rebind the data to the DataList
 Products.DataBind();
}

  UpdateCommand事件处理稍微麻烦一点。它需要从DataKey集合里读取被编辑的product的ProductID,和EditItemTemplate里的TextBox里的product的name和price,然后调用ProductsBLL类的UpdateProduct方法,最后返回到DataList编辑前的状态。

  我们在这里使用 在DataList里编辑和删除数据概述 里的UpdateCommand事件处理代码。

protected void Products_UpdateCommand(object source, DataListCommandEventArgs e)
{
 // Read in the ProductID from the DataKeys collection
 int productID = Convert.ToInt32(Products.DataKeys[e.Item.ItemIndex]);
 // Read in the product name and price values
 TextBox productName = (TextBox)e.Item.FindControl("ProductName");
 TextBox unitPrice = (TextBox)e.Item.FindControl("UnitPrice");
 string productNameValue = null;
 if (productName.Text.Trim().Length > 0)
  productNameValue = productName.Text.Trim();
 decimal? unitPriceValue = null;
 if (unitPrice.Text.Trim().Length > 0)
  unitPriceValue = Decimal.Parse(unitPrice.Text.Trim(),
   System.Globalization.NumberStyles.Currency);
 // Call the ProductsBLL's UpdateProduct method...
 ProductsBLL productsAPI = new ProductsBLL();
 productsAPI.UpdateProduct(productNameValue, unitPriceValue, productID);
 // Revert the DataList back to its pre-editing state
 Products.EditItemIndex = -1;
 Products.DataBind();
}

  在有非法输入的时候— 可能是不正确的price格式,比如“-$5.00”,或者忽略了product的name— 就会引起异常。由于UpdateCommand事件处理还没有处理异常,页面会出现ASP.NET运行时错误。见图3。

在ASP.NET 2.0中怎么处理BLL和DAL异常
图 3: 未处理异常发生时,用户会看到这样的错误页面

第二步: 在UpdateCommand Event Handler里处理异常

  更新流程中,异常可能发生在UpdateCommand事件处理,或BLL或DAL里。比如,如果用户输入了一个“太贵”的价格,UpdateCommand 事件处理里的Decimal.Parse 会抛出FormatException 异常。如果用户忽略了product的name或者price是一个负数,DAL会抛出异常。

当异常发生时,我们希望显示自己定义的信息。添加一个ID为ExceptionDetails的Label控件到页面上,通过设置CssClass属性为Warning CSS类来将Text设置为红色,特大,加粗的意大利字体。这个类在Styles.css文件里定义。

  异常发生时,我们只希望这个 Label显示一次。也就是说,在后面postback的时候,Label的警告信息需要隐藏起来。这个可以通过清除Label的Text属性或者将Visible属性设为False(在Page_Load里)(如我们在在ASP.NET页面中处理BLL/DAL层的异常 里做的那样)或者禁用Label的view state来实现。我们这里用后一种方法。

  异常发生时,我们将异常的信息显示在Label的Text属性上。由于view state被禁用了,后面再postback的话,Text属性会自动的丢失,回到缺省值(空字符串),这样就隐藏了警告信息。

  异常发生时将信息显示在页面上,我们需要在UpdateCommand事件处理里添加Try....Catch块。Try的那部分包含可能抛出异常的代码,Catch部分包含当出现异常时需要执行的代码。更多的Try..Catch块信息参考Exception Handling Fundamentals 。

protected void Products_UpdateCommand(object source, DataListCommandEventArgs e)
{
 // Handle any exceptions raised during the editing process
 try
 {
  // Read in the ProductID from the DataKeys collection
  int productID = Convert.ToInt32(Products.DataKeys[e.Item.ItemIndex]);
  ... Some code omitted for brevity ...
 }
 catch (Exception ex)
 {
  // TODO: Display information about the exception in ExceptionDetails
 }
}

  无论Try块里抛出何种类型的异常,Catch块的代码都会执行。抛出异常的类型—DbException, NoNullAllowedException, ArgumentException等 — 取决于第一个错误。如果是数据库级别的问题,会抛出DbException 。如果是UnitPrice, UnitsInStock, UnitsOnOrder, 或ReorderLevel 字段有非法值,会抛出ArgumentException (我们在ProductsDataTable里已经添加过验证字段值的代码,见创建一个业务逻辑层 )

  我们可以根据捕捉到的异常的类型来为用户提供更好的帮助。下面的代码— 和在ASP.NET页面中处理BLL/DAL层的异常 中基本上一样— 提供了这个功能:

private void DisplayExceptionDetails(Exception ex)
{
 // Display a user-friendly message
 ExceptionDetails.Text = "There was a problem updating the product. ";
 if (ex is System.Data.Common.DbException)
  ExceptionDetails.Text += "Our database is currently experiencing problems.
   Please try again later.";
 else if (ex is NoNullAllowedException)
  ExceptionDetails.Text += "There are one or more required fields that are
   missing.";
 else if (ex is ArgumentException)
 {
  string paramName = ((ArgumentException)ex).ParamName;
  ExceptionDetails.Text +=
   string.Concat("The ", paramName, " value is illegal.");
 }
 else if (ex is ApplicationException)
  ExceptionDetails.Text += ex.Message;
}

  最后仅仅只需要调用DisplayExceptionDetails方法。

  完成Try..Catch后,用户会看到更有用的错误信息,如图4,5所示。注意在异常出现时,DataList仍然保持在可编辑的模式下。这是因为异常发生时,控制流程马上转到Catch块里,忽略了将DataList转到编辑前状态的代码。

在ASP.NET 2.0中怎么处理BLL和DAL异常
图 4: 用户忽略了必填字段时的错误信息

在ASP.NET 2.0中怎么处理BLL和DAL异常
图 5: 输入非法价格时的错误信息

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...