Jquery 为什么在ASP.NET MVC中提交表单时,浏览器中会显示对AJAX帖子的JSON响应?
虽然这可能不是最佳实践,但这是一位朋友教我如何做的,也是我最喜欢的 我使用ajax.post()调用将表单发布到控制器,控制器执行它需要执行的任何操作,然后返回Json:Jquery 为什么在ASP.NET MVC中提交表单时,浏览器中会显示对AJAX帖子的JSON响应?,jquery,asp.net,json,ajax,asp.net-mvc-4,Jquery,Asp.net,Json,Ajax,Asp.net Mvc 4,虽然这可能不是最佳实践,但这是一位朋友教我如何做的,也是我最喜欢的 我使用ajax.post()调用将表单发布到控制器,控制器执行它需要执行的任何操作,然后返回Json: // View @Html.BeginForm() { // whatever form controls are neeeded } <button class="btn btn-default">Create</button> @Html.ActionLink("Cancel", "Ind
// View
@Html.BeginForm()
{
// whatever form controls are neeeded
}
<button class="btn btn-default">Create</button> @Html.ActionLink("Cancel", "Index")
<div class="modal fade" id="modalDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel"></h4>
</div>
<div class="modal-body">
<p class="modal-message"></p>
<p class="modal-message-extra"></p>
</div>
<div class="modal-footer">
<a id="lnkMoreDetail">More Detail</a>
<button id="btnClose" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$("button").click(function() {
$("form").submit();
// I handled this this way, because I'm not sure if the below
// function with an actual submit input type might cause problems...
});
$("form").submit(function () {
if ($(this).valid()) {
$.post($(this).attr("action"), $(this).serialize(), function (data) {
if (!data.IsOK) {
$("h4.modal-title").html(data.Title);
$("p.modal-message").html(data.Message);
$("p.modal-message-extra").html(data.Error).hide();
$("#modalDialog").modal();
// show more detail button only if error value exists
if (data.Error != "") {
$("#lnkMoreDetail").hide();
}
}
else {
// display a modal windows confirming success
// then redirect to the Index view
}
return;
});
return false;
}
});
$("#lnkMoreDetail").on("click", function () {
if ($(this).text() == "More Detail") {
$(this).text("Less Detail");
$("p.modal-message-extra").show();
}
else {
$(this).text("More Detail");
$("p.modal-message-extra").hide();
}
});
</script>
当我提交表单时,我得到以下信息(这是直接从我的浏览器复制的)
{“Message”:“Success”,“IsOK”:true}
很高兴JSON返回正常工作,但为什么它不显示modals?调用create以外的方法。用其他方法(而不是返回的方法)编写控制器逻辑view@coder771你能分享一下你的想法吗?我不明白……javascript中的“else”中发生了什么?@jpgrassi与if语句的第一部分中发生的情况相同,但它显示了一个带有成功消息的模式,然后在短暂延迟后使用setTimeout将用户重定向回列表,以便用户可以实际读取该模式发生的原因,您没有返回视图,而是返回json结果,这就是它显示的内容……检查数据是否==success,然后检查位置是否=location.href
// Controller
[HttpPost]
public ActionResult Create(CreateUserViewModel Source)
{
if (ModelState.IsValid)
{
try
{
// map view model to data model and add to database
return Json(new { Message = "Success", "IsOK = true });
}
catch (Exception ex)
{
// sends a JSON back to the view that details
// the error that occurred
return ReportError(ex, "Register User");
}
}
}