【问题标题】:Receive JSON data within OnComplete event function in Ajax.Beginform在 Ajax.Beginform 的 OnComplete 事件函数中接收 JSON 数据
【发布时间】:2013-02-04 18:43:11
【问题描述】:

我正在尝试使用 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;
        }
   }

【问题讨论】:

  • 将您尝试过的内容添加到您的帖子中
  • 请提供代码示例,以便我们更清楚地了解您所描述的内容。你试过什么?什么有效?你走了多远?一个 JSFiddle 将是理想的,以及您尝试调用的控制器中的一些示例代码。

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


【解决方案1】:

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

当我们使用 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);
}

【讨论】:

  • data 不是我的 json 操作返回的实际数据。它看起来像 xhr ......?不需要获取我需要的“数据”data.responseText 并解析 json 对象。仍然。好答案。谢谢
【解决方案2】:

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

当然,有多种方法可以存储控制器接收到的数据,我建议您使用诸如骨干网模型之类的客户端模型。

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 2014-03-07
    • 2011-10-05
    • 2012-03-18
    • 2011-10-06
    • 2021-07-17
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多