2013-08-20 38 views
1

我在asp.net中編寫web應用程序。我有一個輸入表單。我希望當客戶端在插入前點擊保存按鈕時,檢查這些數據是否在數據庫中。我已經用代碼編寫了它。但我想用java腳本來做這件事,因爲當我使用頁面刷新後面的代碼時。這是檢查重複數據我的.NET代碼:使用javascript檢查重複數據

SqlCommand commandrepeat1 = new SqlCommand("Select code from CmDet where code = " + txtcode.Text + " and company = " + DataBase.globalcompany.ToString() + " order by code desc"); 
      commandrepeat1.Connection = objconnection; 
      objconnection.Close(); 
      objconnection.Open(); 
      SqlDataReader drmax1; 
      drmax1 = commandrepeat1.ExecuteReader(); 
      drmax1.Read(); 
      if (drmax1.HasRows) 
      { 
       MessageBox.Show("Duplicate data . try again!!! "); 
       txtcode.Focus(); 
       objconnection.Close(); 
       return; 
      } 
      objconnection.Close(); 
     } 
     catch 
     { 
      objconnection.Close(); 
     } 

回答

1

你應該有(一旦確定有沒有重複的數據執行服務器端代碼)您的ASP.NET按鈕同時實現OnClick事件OnClientClick事件(執行您的JavaScript將調用以檢查是否有重複的數據)。

我建議如下:

在JavaScript中,jQuery的單擊事件添加到您的按鈕,像這樣:

$("#myButton").click(function() { 

}); 

注:我假設你的按鈕的名稱爲myButton,變化它匹配標記中按鈕的ID。

現在您需要調用服務器端執行邏輯來查找重複數據。我建議使用通過了jQuery .ajax()函數調用ASP.NET AJAX頁面方法,像這樣:

$.ajax({ 
    type: "POST", 
    url: "YourPage.aspx/DoesDataExist", 
    data: "{'codeValue': $('#myTextBox').val()}", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(msg) { 
     if(msg.d) { 
      // This is a duplicate, alert user with message 
      // Block the server-side click from happening with return false; 
      return false; 
     } 
    } 
}); 

最後,我們需要建立服務器端的代碼,將處理由所謂的jQuery網頁上方的方法,如這個:

[WebMethod] 
public static bool DoesDataExist() 
{ 
    SqlCommand commandrepeat1 = new SqlCommand("Select code from CmDet where code = " + txtcode.Text + " and company = " + DataBase.globalcompany.ToString() + " order by code desc"); 
    commandrepeat1.Connection = objconnection; 
    objconnection.Close(); 
    objconnection.Open(); 
    SqlDataReader drmax1; 
    drmax1 = commandrepeat1.ExecuteReader(); 
    drmax1.Read(); 
    if (drmax1.HasRows) 
    { 
     objconnection.Close(); 
     return true; 
    } 
    objconnection.Close(); 

    return false; 
} 
+0

隨時投票給這個答案,當你有足夠的聲譽這樣做。 :-) –

+0

您好卡爾,您只檢查了一個參數'#myTextBoxValue'。如果我必須檢查2-3個參數?我需要照顧什麼樣的事情? – BNN

+0

@stack傳遞給服務器端的ASP.NET AJAX頁面方法的JSON對象將是一個參數(一個對象或只是一個值);另一種選擇是將值作爲查詢字符串參數傳遞。 –