Here is a neat AJAX/Jquery Validation trick. Tell us what you think
With a default.aspx.cs web form with the code behind of:
Code:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Services;
public partial class Recipe3 : System.Web.UI.Page
{
public static string[] UserNameArray;
protected void Page_Load(object sender, EventArgs e)
{
UserNameArray = new string[7] { "Imar Spanjaars", "Lori Lopez", "Leah Venegas", "Lisa Bartell", "Ruth Armandariz", "Frances Callan", "Monica Gildone" };
}
[WebMethod()]
public static bool CheckUserName(string sUserName)
{
foreach (string strUsername in UserNameArray){
if (sUserName == strUsername)
return true;
}
return false;
}
}
Then on the front end in the markup section you have:
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Recipe3.aspx.cs" Inherits="Recipe3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Chapter 6 - Recipe 3: Consuming page methods with AJAX</title>
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function(e) {
e.preventDefault();
if ($("#txtUserName").val() == '')
alert("Please enter the UserName");
else
sendData($("#txtUserName").val());
});
function sendData(sUserName) {
var loc = window.location.href;
loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "Recipe3.aspx" : loc;
$.ajax({
type: "POST",
url: loc + "/CheckUserName",
data: '{"sUserName":"' + sUserName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d)
alert("The User Name is valid");
else
alert("The User Name is invalid")
},
error: function() {
alert("An unexpected error has occurred during processing.");
}
});
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Check User Name" />
</div>
</form>
</body>
</html>
No mention of JSON in your book. Any consideration to using it later on maybe in newer texts for publishing maybe?