在Ajax.Beginform中的OnComplete事件函数中接收JSON数据

Fel*_*lli 3 .net ajax json asp.net-mvc-3

我正在尝试使用Ajax.BeginForm功能.

表单已正确发布,但我需要从我的控制器操作中以json格式检索数据并使用操作结果消息刷新div.

我在Stackoverflow中找到了一些建议,但没有一个是有用的.

这是一个建议:

var data = content.get_response().get_object();
Run Code Online (Sandbox Code Playgroud)

但它对我不起作用.我相信今天已被弃用,仅适用于MVC 2及更低版本.我目前的MVC版本是3.

这是一段代码:

<script type="text/javascript">
   function fnCompleted(data){
    if(data.Success)
    $("#somediv").html(data.StatusMessage).addClass("success");
    else
    $("#somediv").html(data.StatusMessage).addClass("error");
   }
</script>

@{
   var ajaxOptions= new AjaxOptions{
                    OnComplete= "fnCompleted",
                    Url= '@Url.Action("myAction", "myController")',
                    Method= "POST"
 }     

<div id="somediv">/*Here goes the json response*/</div>

using(Ajax.BeginForm(ajaxOptions)){

 @Html.EditorForModel()
 <input type="submit" name="send" value="Send">
Run Code Online (Sandbox Code Playgroud)

}

这是我的控制器动作的一部分:

[HttpPost]
 public JsonResult myAction(MyModel mymodel)
 {
  try
        {
            if (myModel== null)
                throw new Exception("The model is empty");
            if (!ModelState.IsValid)
                throw new Exception("The model is wrong");

            var found = /*Look for existence of the model in the database*/;
            if(found)
                throw new Exception("Already exists the object");

            /*Operation with the database*/

            var result = Json(
                new
                {
                    Success = true,//success
                    StatusMessage = "Object created successfully"
                });
            return result;
        }
        catch (Exception exception)
        {
            var result = Json(
                new
                {
                    Success = false,//error
                    StatusMessage = exception.Message
                });
            return result;
        }
   }
Run Code Online (Sandbox Code Playgroud)

Fel*_*lli 6

对我们获得最佳解释的解释可能是:

当我们使用OnComplete和JSON时,响应将直接嵌入到页面的DOM中.为此目的,建议使用OnSuccess和OnFailure.那些实际上处理来自控制器动作的完美JSON结果.

我告诉你们那些帮助我的链接,这是我之前忽略的,我继续阅读并找到了Joel Purra的答案.

在您的Ajax.BeginForm中:

new AjaxOptions
{
    **OnFailure** = "onTestFailure",
    **OnSuccess** = "onTestSuccess"
}
Run Code Online (Sandbox Code Playgroud)

脚本块:

<script>
//<![CDATA[

function onTestFailure(xhr, status, error) {

    console.log("xhr", xhr);
    console.log("status", status);       

    // TODO: make me pretty
    alert(error);
}

function onTestSuccess(data, status, xhr) {

    console.log("data", data);
    console.log("status", status);
    console.log("xhr", xhr);

    // Here's where you use the JSON object
    //doSomethingUseful(data);
}
Run Code Online (Sandbox Code Playgroud)