通过 jQuery 将 JSON 数据发布到 ASP .NET MVC 4 控制器操作 [英] Posting JSON data via jQuery to ASP .NET MVC 4 controller action

查看:30
本文介绍了通过 jQuery 将 JSON 数据发布到 ASP .NET MVC 4 控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试将复杂的 JSON 对象传递给 MVC 4 控制器操作时遇到问题.由于 JSON 内容是可变的,我不希望 MVC 将 JSON 的各个属性/元素映射到操作方法的参数列表中的参数.我只想在控制器操作中将数据作为单个 JSON 字符串参数获取.

I'm having trouble trying to pass a complex JSON object to an MVC 4 controller action. As the JSON content is variable, I don't want MVC to map individual properties/elements of the JSON to parameters in the action method's parameter list. I just want to get the data as a single JSON string parameter in the controller action.

这是我的操作方法的签名:

Here's the signature of my action method:

    [HttpPost]
    [ValidateInput(false)]
    public string ConvertLogInfoToXml(string jsonOfLog)

这是我尝试从我的浏览器发布一些 JSON 数据的尝试:

And here's my attempt to post some JSON data, from my browser:

    data = {prop: 1, myArray: [1, "two", 3]}; 
    //'data' is much more complicated in my real application
    json = {jsonOfLog: data};

    $.ajax({
        type: 'POST',
        url: "Home/ConvertLogInfoToXml",
        data: JSON.stringify(json),
        success: function (returnPayload) {
            console && console.log ("request succeeded");
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console && console.log ("request failed");
        },
        dataType: "xml",
        contentType: "application/json",            
        processData: false,
        async: false
    });

当我在 ConvertLogInfoToXML 方法的开头遇到断点时,jsonOfLog 为空.

When I hit my breakpoint at the beginning of the ConvertLogInfoToXML method, jsonOfLog is null.

如果我更改 JavaScript 中设置的 'json' 变量,让 jsonOfLog 属性成为一个简单的字符串,例如:

If I change what 'json' variable is set to in the JavaScript to have the jsonOfLog property be a simple string, e.g. :

json = { jsonOfLog: "simple string" };

然后当我在 ConvertLogInfoToXML 方法开头的断点被命中时,jsonOfLog 是字符串的值(例如简单字符串").

then when my breakpoint at the beginning of the ConvertLogInfoToXML method is hit, jsonOfLog is the value of the string (e.g. "simple string").

我尝试将 action 方法中 jsonOfLog 参数的类型更改为 object 类型:

I tried changing the type of the jsonOfLog parameter in the action method to be of type object:

    [HttpPost]
    [ValidateInput(false)]
    public string ConvertLogInfoToXml(object jsonOfLog)

现在,使用原始 JavaScript 代码(我在其中传递更复杂的数据"对象),jsonOfLog 获取 {object} 的值.但是调试器并没有在观察窗口中显示更多细节,我不知道我可以使用什么方法来操作这个变量.

Now, with the original JavaScript code (where I'm passing a more complex 'data' object), jsonOfLog gets the value of {object}. But the debugger doesn't show any more details in a watch window, and I don't know what methods I can use to operate on this variable.

如何将 JSON 数据传递给 MVC 控制器,其中传递的数据是字符串化的复杂对象?

How do I pass JSON data to a MVC controller, where the data passed is a stringified complex object?

谢谢,圣母

推荐答案

问题在于您的 dataTypedata 参数的格式.我刚刚在沙箱中对此进行了测试,结果如下:

The problem is your dataType and the format of your data parameter. I just tested this in a sandbox and the following works:

C#

    [HttpPost]
    public string ConvertLogInfoToXml(string jsonOfLog)
    {
        return Convert.ToString(jsonOfLog);
    }

javascript

<input type="button" onclick="test()"/>

    <script type="text/javascript">

        function test() {
            data = { prop: 1, myArray: [1, "two", 3] };
            //'data' is much more complicated in my real application
            var jsonOfLog = JSON.stringify(data);

            $.ajax({
                type: 'POST',
                dataType: 'text',
                url: "Home/ConvertLogInfoToXml",
                data: "jsonOfLog=" + jsonOfLog,
                success: function (returnPayload) {
                    console && console.log("request succeeded");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console && console.log("request failed");
                },

                processData: false,
                async: false
            });
        }

    </script>

要特别注意data,发送文本时,需要发送一个与你的参数名称相匹配的变量.它不是很漂亮,但它会让你得到你梦寐以求的无格式字符串.

Pay special attention to data, when sending text, you need to send a variable that matches the name of your parameter. It's not pretty, but it will get you your coveted unformatted string.

运行时,jsonOfLog在服务器函数中看起来像这样:

When running this, jsonOfLog looks like this in the server function:

    jsonOfLog   "{"prop":1,"myArray":[1,"two",3]}"    string

HTTP POST 标头:

The HTTP POST header:

Key Value
Request POST /Home/ConvertLogInfoToXml HTTP/1.1
Accept  text/plain, */*; q=0.01
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With    XMLHttpRequest
Referer http://localhost:50189/
Accept-Language en-US
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host    localhost:50189
Content-Length  42
DNT 1
Connection  Keep-Alive
Cache-Control   no-cache
Cookie  EnableSSOUser=admin

HTTP POST 正文:

The HTTP POST body:

jsonOfLog={"prop":1,"myArray":[1,"two",3]}

响应头:

Key Value
Cache-Control   private
Content-Type    text/html; charset=utf-8
Date    Fri, 28 Jun 2013 18:49:24 GMT
Response    HTTP/1.1 200 OK
Server  Microsoft-IIS/8.0
X-AspNet-Version    4.0.30319
X-AspNetMvc-Version 4.0
X-Powered-By    ASP.NET
X-SourceFiles   =?UTF-8?B?XFxwc2ZcaG9tZVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXE12YzRQbGF5Z3JvdW5kXE12YzRQbGF5Z3JvdW5kXEhvbWVcQ29udmVydExvZ0luZm9Ub1htbA==?=

响应正文:

{"prop":1,"myArray":[1,"two",3]}

这篇关于通过 jQuery 将 JSON 数据发布到 ASP .NET MVC 4 控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆