我已经编写了一个Ajax POST来提交表单,但它没有成功。
Ajax POST进入控制器中的操作,然后控制器将返回一个PartialView,这也是正确的,因为我可以调试它。
目标是让用户添加新日志,无论结果如何(验证码失败,验证失败),将返回带有正确ViewBag错误消息的Partialview。剃刀照顾其余部分。这样,用户就不会被重定向到其他页面。
当Ajax成功时,它应该将数据放在正确的<div>
中。代码是一个正在运行的Ajax GET的副本,只是将其更改为POST并提供formdate序列化。
tldr;控制器中的Ajax POST to Action工作,部分视图被渲染并返回但是Ajax失败以使其无法更新指定的<div>
Ajax电话:
<script>
$('#add-log').click(function (event) {
event.preventDefault();
$.ajax({
url: $('#add-log').attr('data-url'),
type: 'post',
data: $("#log-form").serialize(),
succes: function (data) {
$('#add-log').attr('data-target').html(data);
console.log("Succes");
}
});
}
</script>
控制器:
[HttpPost, ValidateInput(false)]
[Authorize(Roles = "Student")]
public ActionResult Add(object sender, Log log, string returnURL, bool SendEmail)
{
ViewBag.Vulns = TempData["Vulns"];
//region Captcha: Here we have our Captcha settings
var response = Request["g-recaptcha-response"];
//secret that was generated in key value pair
const string secret = "Just a secret for our captcha, move along";
var client = new WebClient();
var reply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));
var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);
if (ModelState.IsValid && captchaResponse.Success)
{
db.Log.Add(log);
db.SaveChanges();
if (SendEmail)
{
//Emails are sent from here on out, but that's out of the scope
}
}
else
{
if (!captchaResponse.Success)
{
ViewBag.fillcaptcha = "Please fill in the captcha";
}
else
{
ViewBag.Wrong = "Something went wrong please try again";
}
ViewBag.returnUrl = returnURL;
ViewBag.domain = log.DomainId;
return PartialView(log);
}
}
还有更多代码,但我把它留了下来。控制器中最重要的是最后一个IF。我通过发布没有验证码的空日志来测试ajax,从而导致具有相同日志和viewbag.captcha错误的部分视图。渲染了这个部分视图,但不知何故ajax没有成功。