【问题标题】:check duplicate data with javascript用javascript检查重复数据
【发布时间】:2013-08-22 16:03:32
【问题描述】:

我正在用 asp.net 编写 Web 应用程序。我有一个输入表格。我想当客户端在插入之前单击保存按钮时,检查此数据是否在数据库中。我已经用后面的代码编写了它。但我想用 java 脚本来做这件事,因为当我使用页面刷新后面的代码时。这是我检查重复数据的 .net 代码:

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

【问题讨论】:

    标签: javascript asp.net validation duplicate-data


    【解决方案1】:

    您应该让您的 ASP.NET 按钮同时实现 OnClick 事件(在确定没有重复数据后执行服务器端代码)和 OnClientClick 事件(执行将调用检查是否有重复数据)。

    我建议如下:

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

    【讨论】:

    • 当您有足够的声誉时,请随意对此答案进行投票。 :-)
    • 嗨,karl,您只检查了一个参数#myTextBoxValue。如果我必须检查 2-3 个参数怎么办?我需要处理哪些事情?
    • @stack 传递给服务器端 ASP.NET AJAX 页面方法的 JSON 对象将是一个参数(一个对象或只是一个值);另一种选择是将值作为查询字符串参数传递。
    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2020-03-22
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多