在asp.net中为webservice进行ajax调用(在jquery中)

在asp.net中为webservice进行ajax调用(在jquery中),asp.net,Asp.net,我想使用ajax调用(在jquery中)为编写web方法的webservice验证产品代码的重复性。现在,如果成功函数作为“重复产品代码”执行,则不应允许用户保存记录。那么如何在保存按钮上选中此选项单击事件首先,在代码隐藏页面中创建以下方法 using System.Web.Services; [WebMethod] public static bool CheckDuplicateCode(string productCode) { bool isDuplic

我想使用ajax调用(在jquery中)为编写web方法的webservice验证产品代码的重复性。现在,如果成功函数作为“重复产品代码”执行,则不应允许用户保存记录。那么如何在保存按钮上选中此选项单击事件首先,在代码隐藏页面中创建以下方法

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;
    }
使用System.Web.Services;
[网络方法]
公共静态bool CheckDuplicateCode(字符串productCode)
{
bool isDuplicate=false;
int pCode=Convert.ToInt32(产品代码);
//用数据库检查pCode
List productCodes=GetProductCodeInDb();
foreach(productCodes中的var代码)
{
if(pCode==代码)
{
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>

$(文档).ready(函数(){
$('#')。单击(函数(){
SaveProduct();
});
});
函数SaveProduct(){
//获取要保存的所有数据
var pCode=$('#').val();
//将产品代码传递给web方法以检查是否存在任何重复项
$.ajax({
类型:“POST”,
url:“/InsertProductPage.aspx/CheckDuplicateCode”,
数据:“{'productCode':'”+pCode+“}”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(msg){
AjaxSuccees(味精);
},
错误:ajax失败
});
}
功能AjaxSuccees(msg){
如果(msg.d==true){
返回true;
//插入其余的数据
}
否则{
警报(“产品代码已存在”);
返回false;
}
}
函数AjaxFailed(msg){
警报(result.status+''+result.statusText);
}
希望这有帮助