Ajax.beginform 验证码输入无效时验证码失败

Ajax.beginform with captcha fails when captcha input is invalid

我在 Asp.net MVC4 应用程序中使用带有 @Ajax.BeginForm 的形式使用 CaptchaMvc.Mvc4 1.5.0。当输入有效时,它工作正常。但是当验证码输入无效时。 dispose 方法被调用,我无法重新提交消息。而且验证码图像没有变化。
这是我的看法:

@using CaptchaMvc.HtmlHelpers;
@using CaptchaMvc;
@model Web.Models.Message
@using (Ajax.BeginForm("Contact", "Home", new AjaxOptions
{
       HttpMethod = "post",
       InsertionMode = InsertionMode.Replace,
       UpdateTargetId = "Sent"
}))
{
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <fieldset>                                                        
        @Html.LabelFor(model => model.Message1)
        @Html.TextBoxFor(model => model.Message1)
        @Html.ValidationMessageFor(model => model.Message1)

        @Html.MathCaptcha()

        <input type="submit" value="Create" />
        </fieldset>

        <div id="Sent">
        </div>
}

这是我的操作方法:

[HttpPost]
public ActionResult Contact(Message message)
{
if(this.IsCaptchaValid("error"))           
   if (ModelState.IsValid )
   {
      db.Messages.Add(message);
      db.SaveChanges();
      return RedirectToAction("SuccessfullySent");
   }

ModelState.AddModelError("", "there is some error");
return Content("there is some error");
}

ps:我用@htmal.Beginform测试过,效果很好。一些与@Ajax.Beginform.

相关的问题

诀窍是创建一个局部视图并在其上放置用于生成验证码的代码:

@using CaptchaMvc.HtmlHelpers
@using CaptchaMvc;

<div>
@Html.MathCaptcha()
</div>
<div>
@ViewBag.CaptchaInvalid
</div>
<div>
@ViewBag.Successfully
</div>

并且在 ajax.beginform 放置的主窗体中,在 updateTargetId 上呈现此局部视图 div "Sent":

<div id="Sent">
@{Html.RenderPartial("~/Views/Shared/CaptchaGenerate.cshtml");}
</div>

并在操作方法中进行以下更改:

[HttpPost]
public ActionResult Contact(Message message)
{
  if(this.IsCaptchaValid("error"))           
    if (ModelState.IsValid )
    {
       db.Messages.Add(message);
       db.SaveChanges();
       ViewBag.CaptchaInvalid = "";
       ViewBag.Successfully = "successfully sent";
       return PartialView("~/Views/Shared/CaptchaGenerate.cshtml");
    } 

  ModelState.AddModelError("", "there is some error");
  ViewBag.CaptchaInvalid = "";
  ViewBag.Successfully = "";
  return PartialView("~/Views/Shared/CaptchaGenerate.cshtml");
}