2014-01-24 21 views
3

所以,我試圖使用自定義驗證的用戶名和電子郵件,但它的工作,但只有一個紅色框。它實際上沒有顯示。這是我的代碼遠程驗證顯示紅色框但沒有錯誤信息? ASP - MVC 5

[Required] 
    [Display(Name = "User name")] 
    [System.Web.Mvc.Remote("UserExists", "Account", ErrorMessage = "UserName already exists, please pick another one.")] 
    [Editable(true)] 

控制器... 公共JsonResult UserExists(用戶名字符串) {

 var user = UserManager.FindByName(UserName); 

     return Json(!db.AspNetUsers.Any(x => x.UserName == UserName), 
            JsonRequestBehavior.AllowGet); 
    } 

所以,是的,它顯示的紅色方塊被證明該用戶名存在,但它實際上並沒有顯示錯誤信息。如果我要提交它會顯示錯誤消息,但否則不會。 這是模型..

<script src="~/Scripts/jquery-2.0.3.js"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 
<fieldset> 
    @Html.AntiForgeryToken() 
    <h4>Create a new account.</h4> 
    <hr /> 
    @Html.ValidationSummary() 
    <div class="form-group"> 
     @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" }) 
     <div class="col-md-10"> 
      @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(m => m.UserName) 
     </div> 
+0

是什麼的觀點是什麼樣子?您是否真的輸出錯誤消息'@ H​​tml.ValidationMessageFor(model => model.UserName)' – DGibbs

+0

嘿,我已經更新了它.. –

回答

2

這是你想要實現的功能是什麼:

public JsonResult UserExists(string UserName) { 

    var user = UserManager.FindByName(UserName); 
    if (!db.AspNetUsers.Any(x => x.UserName == UserName)) 
    return Json(true, JsonRequestBehavior.AllowGet); 

    return Json(string.Format("{0} is not available", UserName) , JsonRequestBehavior.AllowGet); 

} 

更新您的遠程標籤這樣的:

[Remote("UserExists", "Account")] 

它只是消除了錯誤消息,基本上除真正的返回以外的任何東西都是發送回客戶端的錯誤消息。

更多信息,請訪問:

http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

+0

歡呼聲的信息,返回錯誤信息絕對是最好的主意。至於我最初的問題,它仍然在做。它仍然只是給出一個紅色框,然後在頁面刷新後給出錯誤信息。 –

+0

好吧,我似乎已經修復它。顯然「@ Html.AntiForgeryToken()」阻止它發出錯誤信息。謝謝你的幫助。 –

+0

請確保您將其添加到控制器的頂部:[OutputCache(Location = OutputCacheLocation.None,NoStore = true)] – hutchonoid