2014-12-28 29 views
2

我正在使用Visual Studio 2013處理ASP.NET動態數據實體項目。我的數據源是基於ADO.NET實體數據模型在SQL Server數據庫上。使用ADO.NET實體數據模型處理ASP.NET動態數據中的數據庫插入衝突

當我嘗試插入違反唯一鍵約束的新表條目時,我得到一個用戶不友好的整個堆棧跟蹤的錯誤頁面。 是否可以在插入視圖中顯示一個簡短的錯誤消息? (類似的錯誤消息時所需要的字段留空)

我嘗試到目前爲止是在延伸下面的代碼Insert.aspx.cs

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) { 
    if (e.Exception == null || e.ExceptionHandled) { 
     Response.Redirect(table.ListActionPath); 
    } 
} 

此(在檢查與異常編號2627)唯一鍵衝突

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) { 
    if (e.Exception == null || e.ExceptionHandled) { 
     Response.Redirect(table.ListActionPath); 
    } 
    else 
    { 
     SqlException innerException = e.Exception.InnerException as SqlException; 
     if (innerException != null) 
     { 
      if (innerException.Number == 2627) 
      { 
       // Violation of unique constraint 
       throw new ValidationException("Unique key violation"); 
      } 
     } 
    } 
} 

雖然Insert.aspx使用一個asp:DynamicValidator我得到以下異常: 「ValidationException未被用戶代碼處理。」

有誰知道該怎麼辦?非常感謝。

回答

0

asp:DynamicValidator必須綁定到特定的控制,以工作(使用ControlToValidate屬性):它會再攔截中出現任何異常(不僅僅是ValidationException),其控制的服務器端事件。

在你的情況我會用一個asp:CustomValidator,而不是採取相應的行動:

ASP.NET頁:

<asp:CustomValidator runat="server" id="myValidationControl" 
    OnServerValidate="myValidationControl_ServerValidate" /> 

代碼隱藏:

private bool _ConstraintViolation = false; 

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) 
{ 
    if (e.Exception == null || e.ExceptionHandled) { 
     Response.Redirect(table.ListActionPath); 
    } 
    else 
    { 
     SqlException innerException = e.Exception.InnerException as SqlException; 
     if (innerException != null) 
     { 
      if (innerException.Number == 2627) 
      { 
       // Violation of unique constraint 
       _ConstraintViolation = true; 
      } 
     } 
    } 
} 

void myValidationControl_ServerValidate (object source, ServerValidateEventArgs a) 
{ 
    if (_ConstraintViolation) 
    { 
     a.IsValid = false; 
     myValidationControl.ErrorMessage = 
     myValidationControl.Text = "Unique key violation"; 
    } 
    else a.IsValid = true; 
} 

你」我需要修改我的代碼到你的頁面(即附上正確的ValidationGroup等),但這應該可以解決您的問題。

相關問題