What am trying to do is to post on form submit to a action and catch response and that works fine.Problem is when RedirectToAction gets called, it just stays on that same view(it doesn't redirect),or in case model is not valid, it doesn't show model validation. So i guess the problem is with url, but how can I correct it?
我想要做的是将表单提交发布到一个动作并捕获响应并且工作正常。问题是当RedirectToAction被调用时,它只停留在同一个视图上(它不会重定向),或者如果模型不是有效,它不显示模型验证。所以我猜问题是网址,但我怎么能纠正呢?
jQuery
$("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);
}
}
});
});
c# asp mvc
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);
}
1 个解决方案
#1
0
Because you're posting your form with an Ajax POST and your in your success function you have alert(response.responseText), you are NOT going to receive a View.
因为您使用Ajax POST发布表单并且在成功函数中有警报(response.responseText),所以您不会收到View。
What you need to do is in success function, take the response from Details action and place it inside an HTML element on the page. Like below:
您需要做的是成功功能,从详细信息操作中获取响应并将其放在页面上的HTML元素中。如下所示:
success: function (response) {
$("#div").html(response);
}
On another note, since you're not using a standard FORM and your posting with JavaScript, you wont get built in validation the models provide.
另一方面,由于您没有使用标准FORM和使用JavaScript发布,因此您不会内置模型提供的验证。
#1
0
Because you're posting your form with an Ajax POST and your in your success function you have alert(response.responseText), you are NOT going to receive a View.
因为您使用Ajax POST发布表单并且在成功函数中有警报(response.responseText),所以您不会收到View。
What you need to do is in success function, take the response from Details action and place it inside an HTML element on the page. Like below:
您需要做的是成功功能,从详细信息操作中获取响应并将其放在页面上的HTML元素中。如下所示:
success: function (response) {
$("#div").html(response);
}
On another note, since you're not using a standard FORM and your posting with JavaScript, you wont get built in validation the models provide.
另一方面,由于您没有使用标准FORM和使用JavaScript发布,因此您不会内置模型提供的验证。