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

时间:2013-02-19 22:06:20

标签: .net ajax json asp.net-mvc-3

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

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

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

这是一个建议:

var data = content.get_response().get_object();

But it didn't work for me。我相信今天已被弃用,仅适用于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">

}

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

[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;
        }
   }

2 个答案:

答案 0 :(得分:6)

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

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

我告诉你们The link that helped me, that was the same I ignored previously,我继续阅读并找到了 Joel Purra的答案。

在你的Ajax.BeginForm中:

new AjaxOptions
{
    **OnFailure** = "onTestFailure",
    **OnSuccess** = "onTestSuccess"
}

脚本块:

<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);
}

答案 1 :(得分:0)

有没有办法将结果存储在视图OnComplete JS函数中?

当然,有多种方法来存储控制器收到的数据我建议你使用像backbone.js模型这样的客户端模型。

使用backbone.js模型可以在客户端存储格式正确的JSON数据对象和集合。

另一种方法是使用隐藏的浏览器变量,少量数据可以存储在隐藏的输入控件中。

另一种方法是使用基于会话的cookie。

编辑:如果客户端MVC类似于使用了backbone.js,则可能需要重新访问您当前的视图设计。但从长远来看,我认为这是有益的。

相关问题