2012-10-30 62 views
1

我做錯了什麼?一切似乎是美好的,但記錄中沒有得到從數據庫中刪除:無法從數據庫中成功刪除記錄

C#

@{ 
    WebSecurity.RequireAuthenticatedUser(); 

    myModel.OSFEntities database = new myModel.OSFEntities(); 

    var productInformation = Request["Pi"]; 

    int productId = Convert.ToInt32(productInformation.Substring(0, productInformation.LastIndexOf("-"))); 
    string productType = productInformation.Substring(productInformation.LastIndexOf("-", productInformation.Length)).Replace("-", String.Empty); 
    var userId = WebSecurity.CurrentUserId; 
    DateTime date = DateTime.Now; 
    int quantity = 1; 
    string quoteId = ""; 

    if (Request["Action"] == "Remove") 
    { 
     if (Session["QuoteId"] != null) 
     { 
      quoteId = (String)Session["QuoteId"]; 

      myModel.Quote quotes = database.Quotes.FirstOrDefault(
       q => q.UserId == userId && q.QuoteId == quoteId && q.ProductId == productId && q.ProductType == productType); 

      database.Quotes.DeleteObject(quotes); 
      database.SaveChanges(); 
     } 
    } 
} 

打字稿:

function RemoveProductFromCart(e) { 
    // Remove from their Cart. 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState == 4) { 
      if (xhr.status == 200) { 
       // The data is now stored in the responseText. 
       // Change value in textbox to 0 so user knows it's been 
       // removed from their cart. 
       var el = <HTMLInputElement>document.getElementById(e.id + "-TB"); 
       if (el != null) { 
        el.value = "0"; 
       } 
      } 

      else { 
       // Server responded with a different response code. 
       alert(xhr.statusText); 
      } 

     } 
    } 

    var parameters = "Pi=" + encodeURIComponent(e.id) + "&" + "Action=Remove"; 

    xhr.open("POST", "../Cart.cshtml"); 
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhr.setRequestHeader("Content-length", parameters.length.toString()); 
    xhr.setRequestHeader("Connection", "close"); 
    xhr.send(parameters); 

    return e.id; 
} 

雖然與F12開發工具進行調試時,我看到:

enter image description here

...這使我相信它是我的C#代碼錯了。爲什麼它不會從數據庫中刪除?

+0

我會** **強烈建議您將所有業務邏輯從您的視圖中取出並存入*至少*控制器中...... – James

+0

這是WebPages **而非MVC **。是的,我儘可能地分開了所有的東西。 – Arrow

+1

對不起,上面的代碼看起來像MVC語法可疑。你有沒有證實你的報價查詢實際上是返回的東西&不爲空? – James

回答

1

我有幾點建議。

在這些情況下,其中一個請求項目與您以前的想法並不完全相同,因此操作或報價ID都可能包含意外。你可以使用斷點來檢查它們。

下一個要檢查的項目是myModel.Quote quotes包含匹配的報價對象。也許你有一個過濾器,即使id是正確的(例如它沒有鏈接到當前用戶,或者產品類型不同等),也可以排除它。

我注意到你正在使用...

database.Quotes.DeleteObject(quotes); 
database.SaveChanges(); 

即您在第一次使用Quotes,而不是第二個:如若SaveChangesDeleteObject電話不能放在對同一語境?

+0

啊,我明白了。是的,這確實很有意義。我原本準備了一篇關於在數據庫中保存更改的文章,這就是他們的代碼是如何工作的,而且它總是有效,所以我沒有真正看到它的任何錯誤。 你是對的,但有關這個驚喜。設置了一個斷點後(由於某種原因,我忘了你可以這樣做)在數量之前有一個領先的空間。我也驚訝沒有拋出任何異常。謝謝Sohnee。 :) – Arrow