我要做的是将表单提交发布到操作并捕获响应,并且工作正常。问题是当RedirectToAction被调用时,它只停留在同一个视图上(它不会重定向),或者万一model无效,不显示模型验证。所以我想问题是网址,但我该如何纠正呢?
$("form").on("submit", function (e) {
e.preventDefault();
var form = $(this);
var formURL = form.attr("action");
$.ajax({
type: "POST",
url: formURL,
data: $(this).serialize(),
success: function (response) {
if (response !== null && response.success == false) {
alert(response.responseText);
}
}
});
});
public ActionResult Add(SomeModel model) {
if (ModelState.IsValid) {
if (true) {
return Json(new { success = false, responseText = "Some error" }, JsonRequestBehavior.AllowGet);
}
return RedirectToAction("Details", new { id = id });
}
//gets called but it doesn't show validation.
return View(model);
}
public ActionResult Details(int id) {
//gets called but it doesn't show the view.
return view(model);
}
答案 0 :(得分:0)
因为您使用Ajax POST发布表单并且您的成功函数中有警报(response.responseText),所以您不会收到视图。
您需要做的是成功功能,从详细信息操作中获取响应并将其放在页面上的HTML元素中。如下所示:
success: function (response) {
$("#div").html(response);
}
另一方面,由于您没有使用标准FORM和使用JavaScript发布,因此您不会内置模型提供的验证。