Preventing duplicate Data with ASP.NET AJAX
- by Yousef_Jadallah
Some times you need to prevent User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form. ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step how to use ASP.NET AJAX with Web Services , you can find it here . Lets go a head with the steps : 1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site. 2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers: This table and this structure just for our example, you can use your own table to implement this approach. 3-Add new Item to your project or website, Choose Web Service file, lets say WebService.cs .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService]) using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public int CheckDuplicate(string User_Name)
{
string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True";
string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name";
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.Parameters.Add("User_Name", User_Name);
con.Open();
int RetVal= (int)cmd.ExecuteScalar();
con.Close();
return RetVal;
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.
4-Add this simple Registration form :
<fieldset>
<table id="TblRegistratoin" cellpadding="0" cellspacing="0">
<tr>
<td>
User Name
</td>
<td>
<asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnRegistration" runat="server" Text="Registration" />
</td>
</tr>
</table>
</fieldset>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.
5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.
<asp:ScriptManager runat="server" ID="scriptManager">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
6-Define the JavaScript code to call the Web Service :
<script language="javascript" type="text/javascript">
// This function calls the Web service method
// passing simple type parameters and the
// callback function
function CallWebMethod() {
var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value;
WebService.CheckDuplicate(User_Name, OnSucceeded, OnError);
}
// This is the callback function invoked if the Web service
// succeeded
function OnSucceeded(result) {
var rsltElement = document.getElementById("lblDuplicate");
if (result == 1)
rsltElement.innerHTML = "This User Name is exist";
else
rsltElement.innerHTML = "";
}
function OnError(error) {
// Display the error.
alert("Service Error: " + error.get_message());
}
</script>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns.
If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :
NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function);
Parameters: you can pass one or many parameters.
Success callback function :handles returned data from the service .
Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.
Hope these steps help you to understand this approach.