2012-05-22 24 views
9

我正在使用遠程驗證在註冊期間檢查我的asp.net mvc 3應用程序(C#)的用戶名是否可用。在mvc中進行遠程驗證的成功響應

我使用MVC遠程屬性驗證爲:

[Remote("IsUserNameAvailable", "User")] 
public string UserName { get; set; } 

當我回到這一點:

return Json(true, JsonRequestBehavior.AllowGet); 

然後,我要像設置隱藏字段的值,這是從行動回報執行的東西或顯示綠色圖標圖像。我也想用真正的ID返回。

如何實現這個目標?

總之,我想做一些成功的事情。爲實現這一

回答

19

一種方法是從驗證動作添加自定義HTTP響應頭:

public ActionResult IsUserNameAvailable(string username) 
{ 
    if (IsValid(username)) 
    { 
     // add the id that you want to communicate to the client 
     // in case of validation success as a custom HTTP header 
     Response.AddHeader("X-ID", "123"); 
     return Json(true, JsonRequestBehavior.AllowGet); 
    } 

    return Json("The username is invalid", JsonRequestBehavior.AllowGet); 
} 

現在在客戶端上,我們顯然對用戶名的標準格式和輸入字段:

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.EditorFor(x => x.UserName) 
    @Html.ValidationMessageFor(x => x.UserName) 
    <button type="submit">OK</button> 
} 

現在拼圖的最後一塊是一個complete處理程序附加到用戶名字段的remote規則:

$(function() { 
    $('#UserName').rules().remote.complete = function (xhr) { 
     if (xhr.status == 200 && xhr.responseText === 'true') { 
      // validation succeeded => we fetch the id that 
      // was sent from the server 
      var id = xhr.getResponseHeader('X-ID'); 

      // and of course we do something useful with this id 
      alert(id); 
     } 
    }; 
}); 
+0

哇....真棒.......非常感謝...... –