2013-08-20 40 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对象将是一个参数(一个对象或只是一个值);另一种选择是将值作为查询字符串参数传递。 –