之前寫過一篇Post用Ajax查詢使用者名稱是否重名,這次我們用JQuery的外掛程式validate來實現,更加簡單,相比之前用xmlhttprequest來說,不用考慮瀏覽器安全色的問題,這也是使用是Jquery這個輕量級架構的特點之一。
此處用的是ASP.NET MVC RC,aspx代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestValidation1.aspx.cs" Inherits="DemoMVCForm.Views.FormDemo.TestValidation1" %>
<!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>Demo</title>
<script src="http://www.cnblogs.com/Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form-sign-up").validate({
rules: {
login: {
required: true,
//here invoke related action
remote: '<%=Url.Action("IsLoginAvailable", "FormDemo") %>'
}
},
messages: {
login: {
required: "請輸入使用者名稱",
remote: jQuery.format("{0} 已經有人用了")
}
},
// set this class to error-labels to indicate valid fields
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
}
});
});
</script>
</head>
<body>
<form action="<%=Url.Action("Register", "FormDemo")%>" method="post" id="form-sign-up">
<h1>Demo表單</h1>
<table id="inputArea">
<tr>
<td>使用者名稱 (試試輸入 Petter):</td>
<td><input type="text" name="login" id="login" /></td>
</tr>
<tr>
<td colspan="2" align="center"><br /><input type="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Asp.net MVC支援Json,所有返回Json的結果,直接使用是JsonResult,看代碼cs,很簡單:
cs
/// <summary>
/// FormDemoController
/// </summary>
/// <remark>Author : PetterLiu 2009-1-12 17:20 DEV-LIUJUNYUAN</remark>
public class FormDemoController : Controller
{
public JsonResult IsLoginAvailable(string login)
{
//TODO: Do the validation
JsonResult result = new JsonResult();
if (login == "Petter")
result.Data = false;
else
result.Data = true;
return result;
}
}
相關引用:
Asp.net MVC http://www.asp.net/mvc
JQuery http://www.jquery.com
jquery-validation http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Author:PetterLiu http://www.cnblogs.com/wintersun/