2016-12-14 34 views
0

To start off with, I did try the information from several links including this one which I thought was the most useful。我試圖確保用戶不輸入已經在數據庫中的電子郵件。我試圖使用Remote屬性,但是從我擁有的代碼中,只要我點擊提交按鈕,什麼都不會發生。這就像我阻止代碼繼續。MVC NET如何檢查用戶名是否存在?我有什麼不工作

這裏是我開始的代碼模型的一部分。 Employee.cs

[Required(ErrorMessage ="Email Address is required.")] 
    [Remote("checkEmailValidate", "Employee", ErrorMessage ="User with this Email already exists")] 
    public virtual string EmailAddress { get; set; } 

這裏是我的控制器的一部分。 EmployeeController.cs

[AllowAnonymous] 
    [HttpPost] 
    public JsonResult checkEmailValidate(string email) 
    { 

     if (checkEmail(email)) 
     { 
      return Json("Email Already Exists!", JsonRequestBehavior.AllowGet); 
     } 
     return Json(true, JsonRequestBehavior.AllowGet); 
    } 

    public Boolean checkEmail(string email) 
    { 

     Employee employee = (from e in db.Employees 
          where e.EmailAddress == email 
          select e).FirstOrDefault(); 
     Console.Write(employee.EmailAddress); 
     if (employee == null) 
     { 
      return true; 
     } 


     return false; 
    } 

這裏是從視圖中的代碼片段。我不確定我是否應該將這些腳本放在那裏。我試圖四處搜尋,但我無法找到明確的答案,但我會把它放在這裏,以便您瞭解我所擁有的東西。

<div class="form-group"> 
     @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { @class = "form-control", placeholder = "Email Address" } }) 
      @Html.ValidationMessageFor(model => model.EmailAddress, "", new { @class = "text-danger" }) 
     </div> 
    </div> 
    <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> 

任何幫助將受到歡迎。再次,當我點擊按鈕提交新用戶的信息時,似乎沒有任何事情發生。我想要發生的事情是,在他們輸入電子郵件的框上方或旁邊出現一些紅色文字,告訴他們它已經存在。

如果有像在同一個頁面上彈出一個警告,使其不會抹去,他們把其他的信息,將一併接受一個更簡單或「便宜」的方式。謝謝!

+2

看起來你有你的返回值向後在'CheckEmail'方法。 – krillgar

+0

Woops!改變它,但我仍然有同樣的問題,雖然 –

回答

0

如此看來,我的錯誤是用論據checkEmailValidate方法。我不知道這是如何工作的,但似乎我需要使參數變量名稱與控制器中的名稱相同。因此,與

public virtual string EmailAddress { get; set; } 

我需要確保checkEmailValidate這個樣子checkEmailValidate(string emailAddress)而非checkEmailValidate(string email)

+1

是的。您的POST方法的參數需要與您的HTML元素上的'name'屬性匹配。 – krillgar

相關問題