JQuery+Asp.net MVC實現使用者名稱重名查詢

iDotNetSpace發表於2009-02-09
之前寫過一篇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>Demotitle>
    
<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: ''
                    }
                },
                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="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,很簡單:

JQuery+Asp.net MVC實現使用者名稱重名查詢cs
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  /// 
    
/// FormDemoController
    
/// 
    
/// Author : PetterLiu 2009-1-12 17:20  DEV-LIUJUNYUAN
    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;
        }
    }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-545674/,如需轉載,請註明出處,否則將追究法律責任。

相關文章