2015-07-20 82 views
-1

我做我的MVC模式使用遠程屬性的遠程驗證,請看下面的代碼:模型 - 視圖 - 遠程驗證

[Required] 
[System.Web.Mvc.Remote("IsEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "The Email Already Exists")] 

在控制器的操作方法我使用電子郵件的用戶輸入的參數,與DB檢查,請看下面的代碼:

public JsonResult IsEmailExist(string emailAddress) 
{ 
    using (var db = new YouTubeNZ())             
    { 
     var isExist = !db.Users.Any(X => X.EmailAddress == emailAddress);           
     return Json(isExist, JsonRequestBehavior.AllowGet);             
    } 
}    

但在運行時的操作方法的參數是「空」時的值應該是用戶輸入電子郵件地址,它是沒有得到驗證現有電子郵件。

+1

什麼是電子郵件的輸入字段的名稱屬性? – MstfAsan

+0

顯示您將此應用於的屬性 - 它需要是「public string emailaddress' –

回答

0

確保您HttpPost ATTR裝飾你的操作方法,和你的屬性名稱的方法參數匹配(即:EmailAddress):

[HttpPost] 
public JsonResult IsEmailExist(string emailAddress) 
{ 
    using (var db = new YouTubeNZ())             
    { 
     var isExist = !db.Users.Any(X => X.EmailAddress == emailAddress);           
     return Json(isExist, JsonRequestBehavior.AllowGet);             
    } 
} 
0

請確保以下幾點。

你的模型屬性應該像

[Required] 
[System.Web.Mvc.Remote("IsEmailExist", "Account", ErrorMessage = "The Email Already Exists")] 
public string EmailAddress { get; set; } 

也能改變你AccountsController操作方法

public ActionResult IsEmailExist(string emailAddress) 
{ 
    using (var db = new YouTubeNZ())             
    { 
     bool isExist = !db.Users.Any(X => X.EmailAddress == emailAddress);           
     return Json(isExist, JsonRequestBehavior.AllowGet);             
    } 
} 
0
Your Model should be like this 

[Required] 
[Remote("IsEmailExist","Account",ErrorMessage="This Email is already exists")] 
public string EmailAddress{get;set;} 

And Controller should be like this 

public JsonResult IsEmailExist(string emailAddress) 
{ 
    return Json(isExist(emailAddress),JsonRequestBehavior.AllowGet); 
} 

private bool isExist(string emailAddress) 
{ 
    using (var db = new YouTubeNZ())             
    { 
     return !db.Users.Any(X => X.EmailAddress == emailAddress); 
    } 
}