好的,我明白了。這個tutorial是非常有幫助的,因爲我在第一篇文章中提到的那個沒有做好解釋。下面是我的盤帶代碼:
的ContactController:
[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("[email protected]");
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。我希望這可以幫助像我一樣可能遇到同樣問題的人。
這些都是我的文件夾: 屬性, 參考, 的App_Data, App_Start, 內容, 控制器, 過濾器, 圖片, 模型, 腳本, 意見。 本教程沒有顯示它在View或Controller中使用時如何引用這些.cs文件。 – 2myCharlie
NuGet ** Google reCAPTCHA V2 ** for MVC 4 and 5 - [NuGet Package](https://www.nuget.org/packages/reCAPTCH.MVC/) - [Demo And Document](http:///recaptchamvc.apphb.com/) – Sender