2011-09-21 41 views

回答

1

首先,在後面的頁面代碼中創建下面的方法。

using System.Web.Services; 

[WebMethod] 
    public static bool CheckDuplicateCode(string productCode) 
    { 
     bool isDuplicate = false; 

     int pCode = Convert.ToInt32(productCode); 

     //check pCode with database 
     List<int> productCodes = GetProductCodeInDb(); 

     foreach (var code in productCodes) 
     { 
      if (pCode == code) 
      { 
       isDuplicate = true; 
       break; 
      } 
     } 
     return isDuplicate; 
    } 

,並在頁面標記結束body標籤插入

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#<%=btnSave.ClientID %>').click(function() { 
      SaveProduct(); 
     }); 
    }); 

    function SaveProduct() { 

     //Get all the data that you are trying to save 
     var pCode = $('#<%= txtProductCode.ClientID %>').val(); 

     //pass the product code to web method to check for any duplicate 
      $.ajax({ 
       type: "POST", 
       url: "/InsertProductPage.aspx/CheckDuplicateCode", 
       data: "{'productCode': '" + pCode + "'}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (msg) { 
        AjaxSuccees(msg); 
       }, 
       error: AjaxFailed 
      }); 
     } 

     function AjaxSuccees(msg) { 
      if (msg.d == true) { 
        return true; 
       //insert the rest of data 
      } 
      else { 
       alert("Product code already exists"); 
       return false; 
      } 
     } 

     function AjaxFailed(msg) { 
      alert(result.status + ' ' + result.statusText); 
     } 
</script> 

希望之前這段代碼這有助於