好的,我明白了。本教程非常有帮助,因为我在最初的帖子中提到的那个没有很好地解释。以下是我的编码:
联系人控制器:
[CaptchaValidator]
[HttpPost]
public ActionResult ContactForm(ContactModels model, bool captchaValid)
{
if (!captchaValid)
{
ModelState.AddModelError("captcha", "You did not type the verification word correctly. Please try again.");
}
else if(ModelState.IsValid)
{
MailMessage netMessage = new MailMessage();
SmtpClient mailClient = new SmtpClient();
try
{
netMessage.From = new MailAddress("contact@myComp.com");
netMessage.To.Add(new MailAddress(model.email));
netMessage.IsBodyHtml = true;
netMessage.Priority = MailPriority.High;
netMessage.Subject = "Subject: " + model.subject;
netMessage.Body = getMailBody(model.fstName, model.lstName, model.subject, model.phone, model.email, model.address, model.apartment, model.city, model.state, model.zipcode, model.country, model.comments);
mailClient.Send(netMessage);
}
catch (Exception error)
{
Response.Write("Error sending email: " + error.Message + "<br /> StackTrace: " + error.StackTrace);
}
finally
{
netMessage.Dispose();
netMessage = null;
mailClient = null;
}
return RedirectToAction("Index", "Home");
}
return View();
}
这是我的观点:
@using MvcReCaptcha.Helpers;
@{
ViewBag.Title = "Contact";
Layout = "~/Views/Shared/_FullPage.cshtml";
}
<h2>Contact Us</h2>
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.fstName)
@Html.TextBoxFor(model => model.fstName)
@Html.ValidationMessageFor(model => model.fstName)
@Html.LabelFor(model => model.lstName)
@Html.TextBoxFor(model => model.lstName)
@Html.ValidationMessageFor(model => model.lstName)
@Html.LabelFor(model => model.phone)
@Html.TextBoxFor(model => model.phone)
@Html.LabelFor(model => model.email)
@Html.TextBoxFor(model => model.email)
@Html.LabelFor(model => model.address)
@Html.TextBoxFor(model => model.address)
@Html.LabelFor(model => model.apartment)
@Html.TextBoxFor(model => model.apartment)
@Html.LabelFor(model => model.city)
@Html.TextBoxFor(model => model.city)
@Html.LabelFor(model => model.state)
@Html.TextBoxFor(model => model.state)
@Html.LabelFor(model => model.zipcode)
@Html.TextBoxFor(model => model.zipcode)
@Html.LabelFor(model => model.country)
@Html.TextBoxFor(model => model.country)
@Html.LabelFor(model => model.subject)
@Html.TextBoxFor(model => model.subject)
@Html.LabelFor(model => model.comments)
@Html.TextAreaFor(model => model.comments)
@Html.Raw(Html.GenerateCaptcha())
@Html.ValidationMessage("captcha")
<br />
<button type="submit">Submit</button>
}
注意到@html.ValidationMessage 中的参数与ModelStae.AddModelError 中的参数匹配。我希望这可以帮助可能遇到与我相同问题的人。