我对一个返回JSON的方法使用AJAX调用。如何在不重定向到新的空页面的情况下读取返回的JSON?
[HttpPost]
public JsonResult Test()
{
return Json("JSON return test", JsonRequestBehavior.AllowGet);
}
@model List<POC.Web.Intranet.Models.AttachmentPropertyViewModel>
<div>
@using (Ajax.BeginForm("Test", "DMS", new AjaxOptions { HttpMethod = "POST", OnSuccess = "endMethod()", OnBegin = "beginMethod()" }))
{
<h6>Properties</h6>
for (int i = 0; i < Model.Count; i++)
{
@Html.HiddenFor(item => item[i].AttachmentPropertyId);
@Html.HiddenFor(item => item[i].AttachmentMetaDataId);
<label>@Model[i].AttachmentPropertyName</label>
@Html.TextBoxFor(item => item[i].AttachmentPropertyValue, htmlAttributes: new { @class = "form-control property-value-txtbox" });
<br />
}
<input type="submit" id="btnSaveChanges" value="Save Chnages" />
}
<hr />
</div>
<script>
function beginMethod() {
alert("Start");
}
function endMethod() {
alert("Finish");
// also here i want to read the incoming json
}
</script>
答案 0 :(得分:2)
首先,您不需要JsonRequestBehavior.AllowGet
,因为您提出POST
请求。
[HttpPost]
public JsonResult Test()
{
return Json("JSON return test");
}
然后,改变这个:
OnSuccess = "endMethod()", OnBegin = "beginMethod()"
要
OnSuccess = "endMethod", OnBegin = "beginMethod"
在您的脚本中,传递response
参数以从json
获取controller
结果。
function endMethod(response) {
console.log(response);
alert("Finish");
// also here i want to read the incoming json
}
答案 1 :(得分:0)
您可以按照以下两种方法之一停止重定向并执行Ajax调用。
从提交将按钮类型更改为按钮。
或者通过使用下面的代码段来阻止提交表单的默认操作,在表单提交上调用JavaScript函数,