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

查看:142
本文介绍了发布通过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为null。

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

如果我改变什么JSON变量在JavaScript中设置有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").

我试图在操作方法改变jsonOfLog参数的类型为类型的对象:

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 code(在那里我传递一个更为复杂的数据对象),jsonOfLog获取{}对象的价值。但调试器不会显示在监视窗口的更多细节,我不知道我可以用什么方法来对这个变量进行操作。

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?

谢谢,
巴黎

推荐答案

问题是你的的dataType 和您的数据格式参数。我只是在沙箱中测试了这个和以下工作:

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的

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>

特别注意数据,发送短信时,你需要发送你的参数名称相匹配的变量。这不是pretty,但它会得到你梦寐以求的字符串格式化

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天全站免登陆