0

I want to validate product code for duplication using ajax call(in jquery) for webservice in which web method is written. now if success function executes as 'duplicate product code' it should not allow the user to save record. so how can i check this on Save buttons click event

1 Answer 1

1

First, create the below method in the page code behind.

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;
    }

And in the page markup just before the end body tag insert this code

 <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>

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.