2
votes

Im using CaptchaMvc.Mvc4 1.5.0 in a form with @Ajax.BeginForm in my Asp.net MVC4 application. when input is valid it works fine. but when captcha input is invalid. dispose method is called and i cant resubmit the message. and the captcha image dosnt change.
This is my View:

@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>
}

And this is my Action method:

[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: I tested it with @htmal.Beginform and it worked fine. some how problem is related to @Ajax.Beginform.

1

1 Answers

-1
votes

the trick is create a partial view and put code for generate captcha on it :

@using CaptchaMvc.HtmlHelpers
@using CaptchaMvc;

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

and in the main form where the ajax.beginform is put rendering this parcial view on the updateTargetId div "Sent":

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

and in the action method make this changes:

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