简体   繁体   English

MVC4 ajax调用并正确返回数据

[英]MVC4 ajax call and return data properly

I invoke an action in a controller using ajax like below. 我使用如下所示的ajax在控制器中调用动作。

$.ajax({
            type: "POST",
            url: "getUserInfo.json",
            data: "",
            success: function (data) {
                if (data.resultInfo.result != "SUCCESS") { alert("error"); return; }
                setUserInfo(data.userInfo);

                //alert(data.resultInfo.result);
                //alert(data.resultInfo.message);

                settingMenu();
                //historyBackProc(); //histroyback catch
            },
            error: function (data) {
                alert(data.resultInfo.message);
            }
});

And what it ends up calling is this action. 最终调用的是此操作。

public ActionResult getUserInfo()
        {
            if ( Session["UserInfo"] != null ) {
                ViewData.Add("resultInfo", new resultInfo("SUCCESS"));
                ViewData.Add("UserInfo", Session["UserInfo"]);
                return Json(ViewData);
            }
            else
            {
                return RedirectToAction("index.mon");
            }
        }

and back to the ajax success callback, the data isn't what I want it to be. 回到ajax成功回调,数据不是我想要的。

What I want is, 我想要的是

data
 - "resultInfo" : object
 - "UserInfo" : object

But it ended up having just objects, not keys. 但是最终它只有对象,而不是键。

data
 - object[0]
   - Key : "resultInfo"
   - Value : object
 - object[1]
   - Key : "UserInfo"
   - Value : object

To achieve this, how to manipulate the return object in the action? 为此,如何在动作中操纵返回对象? I need to do this to run this web application with the absolutely same javascript in both JAVA and .NET environment. 我需要这样做,才能在JAVA和.NET环境中使用完全相同的javascript运行此Web应用程序。

There is no need to use ViewData when you are returning JSON. 返回JSON时无需使用ViewData You are getting result since ViewData is a dictionary. 因为ViewData是字典,所以您正在获得结果。

Use 采用

return Json(new {
    resultInfo = new resultInfo("SUCCESS"),
    UserInfo = Session["UserInfo"]
});

instead of 代替

ViewData.Add("resultInfo", new resultInfo("SUCCESS"));
ViewData.Add("UserInfo", Session["UserInfo"]);
return Json(ViewData);
        Dim data As New SortedDictionary(Of String, String)
        data.add("key","value")
        data.add("key2","value2")
        Dim serializer As New JavaScriptSerializer()
        Return serializer.Serialize(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM