当验证码输入无效时,带验证码的Ajax.beginform失败

时间:2015-03-01 05:57:56

标签: asp.net ajax asp.net-mvc-4 captcha

我在我的Asp.net MVC4应用程序中使用带有@ Ajax.BeginForm的表单使用CaptchaMvc.Mvc4 1.5.0。当输入有效时,它工作正常。但是当验证码输入无效时。调用dispose方法,我不能重新提交消息。并且验证码图像dosnt更改 这是我的观点:

@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有什么关系。

1 个答案:

答案 0 :(得分:-1)

诀窍是创建一个局部视图并放置代码以生成验证码:

@using CaptchaMvc.HtmlHelpers
@using CaptchaMvc;

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

并在主表单中放置ajax.beginform,在updateTargetId div上呈现此parcial视图&#34;已发送&#34;:

<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");
}