我是使用 Entity Framework 的 Asp.Net Mvc4 新手。现在我正在为忘记密码进行验证码验证。作为我的代码,当我单击提交按钮时,即使验证码无效,也会将电子邮件 ID 值传递给 Controller 。如果验证码正确,我想将电子邮件 ID 值传递给 Controller ,否则它应该显示验证错误,并且应该重新加载新验证码。请帮我解决它。提前致谢。
这是我用于生成和验证验证码的 Java 脚本代码:
var captchastring = '';
function getCaptcha() {
var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
var string_length = 7;
captchastring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
captchastring += chars.substring(rnum, rnum + 1);
}
document.getElementById("randomfield").innerHTML = captchastring;
}
function validation() {
var text2 = document.getElementById("txtcode").value;
if (text2 == captchastring) {
var email = document.getElementById("UserEmail").value;
x = document.getElementById("demo");
// Find the element
x.innerHTML = "valid";
x.style.color = "#ff0000";
}
else {
x = document.getElementById("demo"); // Find the element
x.innerHTML = "Invalid Captcha. Try again";
x.style.color = "#ff0000";
}
}
</script>
这是我的 cshtml 代码正文:
<div class="col-md-5">
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<h5 class="nomargin">Forgot Password</h5>
@Html.TextBoxFor(u => u.UserEmail, new { @class = "form-control", placeholder = "Email" })
<br />
<div id="captcha">
<div id="captcha_gen">
<label id="randomfield">
</label>
</div>
<button type="button" onclick="getCaptcha();" style="border: 0; background: transparent;float:right; position:relative";>
<img src="../../Content/FSLBootstrapUI/images/playback_reload.png" width="25" height="25" alt="submit" />
</button>
</div>
<input type="text" id="txtcode" class="form-control" placeholder="Enter code here" />
<button class="btn btn-success btn-block" value="submit" onclick="validation()">Reset</button> <p id="demo"> </p>
}
</div>
最佳答案
目前发生了什么?我的意思是,应用程序的行为如何? 编辑: 您可以尝试服务器端验证,例如,如果您有一个要验证的字段,则可以在其中添加验证标签。例如:
<input type="text" name="SampleTextBox" id="SampleTextBoxId"/>
@Html.ValidationMessage("SampleTextBox", "*")
然后你到 Controller 并添加这样的代码:
if (!string.IsNullOrEmpty(SampleTextBox))
{
//Your Code.
}
else
{
ViewData.ModelState.AddModelError("SampleTextBoxId", "Text should not be empty.");
}
使用Model.IsValid
作为编写主代码的条件。
如果执行 ViewData.ModelState.AddModelError("SampleTextBoxId", "Text should not beempty.");
,Model.IsValid
将变为 False。
这是添加验证的一种方法。您可以在 Controller 本身中检查有效/无效的验证码并抛出错误。
例如:
if (IsValidCaptcha(enteredCaptcha))
{
//Code
}
else
{
ViewData.ModelState.AddModelError("captchaId", "Enter valid captcha");
}
最后,将验证摘要添加到您的页面
@Html.ValidationSummary("Error Messages")
关于javascript - 如何在Asp.Net Mvc4中检查验证码后传递Email Id值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22225419/