【发布时间】:2015-12-17 01:11:52
【问题描述】:
我的 MVC 4 页面有一个验证码控件,如果输入不正确,我无法让它显示一条消息。我习惯于通过 jquery 做事并成功做某事,但是当我在这里做类似的事情时,我失去了 ModelState.IsValid。
因此,当我运行此代码时,Captcha 控件在页面上加载良好,它在图像中显示 5 个字母,其中一行显示“刷新”,并在其下方有一个文本框,用于在我的索引页面上使用提交按钮进行输入发布到控制器。
当我输入错误时,它会刷新图像而没有任何消息表明有任何错误,我知道这是错误的,因为我的控制器说 ModelState.IsValid 为假,但我想加载新图像并显示输入不正确。
当我输入正确时,它会刷新图像,但仍然没有消息或任何内容。我希望它留在那里并说输入正确并禁用文本框。
我的问题:我该如何做我上面描述的事情?
我的代码如下:
控制器/HomeController.cs
using System.Web.Mvc;
using CaptchaDemo.MVC4.ViewModels;
using CaptchaMvc;
using CaptchaMvc.Attributes;
using CaptchaMvc.Infrastructure;
namespace CaptchaDemo.MVC4.Controllers
{
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
CaptchaUtils.CaptchaManager.StorageProvider = new CookieStorageProvider();
ViewBag.Title = "Captcha MVC 4 Demo";
return View();
}
public ActionResult _Captcha()
{
CaptchaViewModel model = new CaptchaViewModel();
return View(model);
}
public ActionResult AjaxForm()
{
return View(new CaptchaViewModel());
}
[HttpPost, CaptchaVerify("Captcha is not valid")]
public ActionResult AjaxForm(CaptchaViewModel model)
{
if (ModelState.IsValid)
{
ModelState.Clear();
TempData["Message"] = "Message: captcha is valid.";
model.strMessage = "efefwf";
if (Request.IsAjaxRequest())
return PartialView("_Captcha", model);
//return Json(model, JsonRequestBehavior.AllowGet);
return View(model);
}
TempData["ErrorMessage"] = "Error: captcha is not valid.";
if (Request.IsAjaxRequest())
return PartialView("_Captcha", model);
return View(model);
}
}
}
ViewModels/CaptchaViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CaptchaDemo.MVC4.ViewModels
{
public class CaptchaViewModel
{
public string strMessage { get; set; }
}
}
Views/Home/Index.cshtml
@using (Html.BeginForm("AjaxForm", "Home", FormMethod.Post, new { @id = "AjaxCaptchaForm", @class = "ajax" }))
{
<div id="update">@Html.Partial("_Captcha")</div>
<input type="submit" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#AjaxCaptchaForm').submit(function () {
$.post($(this).attr("action"), $(this).serialize(), function (results) {
$("#update").html(results);
});
return false;
});
});
</script>
视图/共享/_Captcha.cshtml
@using CaptchaMvc.HtmlHelpers
@model CaptchaDemo.MVC4.ViewModels.CaptchaViewModel
@Html.ValidationSummary(true)
@Html.ValidationMessageFor(model => model.strMessage)
@Html.Captcha(5)
<span>@Model.strMessage</span>
【问题讨论】:
-
我能够让它显示错误输入的消息,但仍然没有正确输入的运气。
标签: c# jquery asp.net-mvc-4 razor captcha