2017-01-03 133 views
2

我对返回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

它被触发'beginMethod'? –

+0

输入'type =“submit”'将表单提交给控制器。所以把它改为'button' – Qsprec

+0

这必须是stackoverflow上最常问的问题。 – philantrovert

回答

0

您可以停止重定向和执行您的Ajax按照下面给出的两种方法之一调用。

  1. 按钮类型从更改为按钮提交

  2. 或者调用形式通过防止利用下面的代码片段提交表单的默认操作提交的JavaScript函数,

2

首先,你做不需要JsonRequestBehavior.AllowGet,因为你做了POST请求。

[HttpPost] 
public JsonResult Test() 
{ 
    return Json("JSON return test"); 
} 

然后,改变这种:

OnSuccess = "endMethod()", OnBegin = "beginMethod()" 

OnSuccess = "endMethod", OnBegin = "beginMethod" 

而在你的脚本,通过response参数从controller得到json结果。

function endMethod(response) { 
    console.log(response); 
    alert("Finish"); 
    // also here i want to read the incoming json 
}