的情況下
解決方案是將MVC標準驗證屬性[Remote]與處理這些客戶端驗證請求的控制器結合使用。
該解決方案完全基於此Microsoft article。
快速求和式:使用[遠程]屬性指定控制器,並得到行動
標註您的視圖模型屬性被稱爲:
[Required]
[Display(Name = "E-Mail")]
[EmailAddress]
[System.Web.Mvc.Remote("EMail_Available", "Validation")]
public string Email { get; set; }
創建具有控制器輸出緩存禁用:
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class ValidationController : Controller
{
public ValidationController() {}
// GET: Validation
[AllowAnonymous]
public async Task<JsonResult> EMail_Available(string EMail) {
var user = await UserManager.FindByEmail(EMail);
if (user == null)
return Json(true, JsonRequestBehavior.AllowGet);
string suggestedUID = String.Format(CultureInfo.InvariantCulture,
"Die E-Mail '{0}' wurde bereits registriert.", EMail);
return Json(suggestedUID, JsonRequestBehavior.AllowGet);
}
}
In您的Razor視圖提供@ Html.ValidationMessageFor(...)
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-4 control-label" })
<div class="col-md-8 input-group">
<span class="input-group-addon colorLogin"><span class="glyphicon glyphicon-envelope" id="spaces"></span></span>
@Html.TextBoxFor(m => m.Email, new { @id = "register_email", @class = "form-control", @placeholder = "E-Mail", @autofocus = "" })
@Html.ValidationMessageFor(m => m.Email, "", new { @id = "register_email_error", @class = "text-danger" }, "div")
</div>
</div>
你做服務器的請求做客戶端驗證?似乎對我毫無意義。驗證客戶端上的客戶端數據和服務器上的所有驗證。你的自定義驗證器是做什麼的? – heymega
您可以使用遠程方法,還是僅僅使用服務器方法返回結果,您的方法還有更多嗎? http://jqueryvalidation.org/remote-method –
我需要檢查輸入的電子郵件地址是否尚未使用。在輸入數據時而不是在提交表單時觸發客戶端驗證。因此用戶立即獲得反饋。我需要檢查是否可以使用遠程方法。 – rherzog