问题
i am writing web application in asp.net . i have a input form . i want when the client click on save Button before insert, check this data is in data base or not . i have written it with code behind . but i want do this with java script because when i i use code behind the page refresh . this is my .net code for check duplicate data:
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:
You should have your ASP.NET button implement both the OnClick
event (to execute server-side code once it is determined that there is not duplicate data) and OnClientClick
event (to execute your JavaScript that will call to check if there is duplicate data).
I suggest the following:
In JavaScript, add a jQuery click event to your button, like this:
$( "#myButton" ).click(function() {
});
Note: I have assumed the name of your button to be myButton
, change it to match the ID of your button in markup.
Now you will need to call server-side to execute your logic to look for duplicate data. I recommend using ASP.NET AJAX Page Methods invoked via the jQuery .ajax()
function, like this:
$.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;
}
}
});
Finally, we need to build the server-side code that will handle the page method called by the jQuery above, like this:
[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;
}
来源:https://stackoverflow.com/questions/18337844/check-duplicate-data-with-javascript