In this post we are going to use Jquery to check whether a string is exists in a given list. You can also use this method to check the string availability in your database table as well.
First add a handler class to your project and name it as "LoginHandler.ashx"
<%@ WebHandler Language="C#" Class="LoginHandler" %>
using System;
using System.Web;
public class LoginHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string uname = context.Request["uname"];
string result = "0";
if (uname != null)
{
result = CheckAvailability(uname);
}
context.Response.Write(result);
context.Response.End();
}
public string CheckAvailability(string name)
{
string result = "0";
System.Collections.Generic.List<string> lst = new System.Collections.Generic.List<string>();
lst.Add("chamara");
lst.Add("janaka");
lst.Add("lahiru");
foreach (string item in lst)
{
if (item == name)
{
result = "1";
break;
}
}
return result;
}
public bool IsReusable
{
get
{
return false;
}
}
}
CheckAvailability()
This method accepts the parameter uname from POST method and check the string through the list. Then it returns the string "0" if the parameter value not exists in the list or "1" if it exists.
Below is our web form
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.8.3.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
$("#btnAvailability").click(function () {
$.post("LoginHandler.ashx", { uname: $("#<% =txtName.ClientID %>").val() }, function (result) {
if(result=="1")
{
$("#dvMsg").html("Name already taken!");
}
else if (result == "0") {
$("#dvMsg").html("Available");
}
else {
$("#dvMsg").html("Error!");
}
});
});
$("#btnAvailability").ajaxError(function (event, request, settings, error) {
alert("Error requesting page " + settings.url + " Error:" + error);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input type="button" id="btnAvailability" value="Check Availability" />
<div id="dvMsg"></div>
</div>
</form>
</body>
</html>
We pass the text in "txtName" as a POST parameter to the handler and gets the response to the "result" variable then display the message according to the result.
Sunday, December 9, 2012
Check String availability using ASP.NET and Jquery.
Subscribe to:
Post Comments (Atom)
No comments:
Write comments