通过jQuery发布JSON数据到asp.net MVC 4控制器操作。

时间:2022-12-01 23:34:32

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.

我很难将复杂的JSON对象传递给MVC 4控制器操作。由于JSON内容是可变的,所以我不希望MVC将JSON的单个属性/元素映射到action方法的参数列表中的参数。我只想把数据作为一个JSON字符串参数在控制器操作中。

Here's the signature of my action method:

以下是我的行动方法的签名:

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

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

我尝试在浏览器中发布一些JSON数据:

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

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

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

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

如果我更改JavaScript中设置的“json”变量,使jsonOfLog属性是一个简单的字符串,例如:

json = { jsonOfLog: "simple string" };

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

然后,当我在ConvertLogInfoToXML方法的开始处的断点被命中时,jsonOfLog就是字符串的值(例如)。“简单的字符串”)。

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

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

    [HttpPost]
    [ValidateInput(false)]
    public string ConvertLogInfoToXml(object 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.

现在,有了原始的JavaScript代码(我正在传递一个更复杂的“data”对象),jsonOfLog将获得{object}的值。但是调试器没有在监视窗口中显示更多的细节,我不知道我可以使用什么方法来操作这个变量。

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

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

Thanks, Notre

谢谢,我们的

6 个解决方案

#1


23  

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

问题在于数据类型和数据参数的格式。我刚刚在一个沙箱里测试了这个,下面的工作如下:

C#

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>

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.

在发送文本时,要特别注意数据,您需要发送一个与参数名称匹配的变量。它并不漂亮,但是它会让你得到你梦寐以求的未格式化的字符串。

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

运行时,jsonOfLog在服务器函数中是这样的:

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

The HTTP POST header:

HTTP POST头:

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

The HTTP POST body:

HTTP POST的身体:

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

The response header:

响应头:

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==?=

The response body:

响应身体:

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

#2


2  

I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?

如果你参考这篇文章,你会找到你的答案:将JSON反序列化为c#动态对象?

There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.

实现你想要的东西有很多种方法。System.Web.Helpers。Json方法(一些答案)似乎是最简单的。

#3


2  

VB.NET VERSION

Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

好了,我花了几个小时寻找一个可行的方法,将多个参数发布到MVC 4 WEB API中,但我发现的大部分内容要么是“GET”操作,要么就是干脆不工作。然而,我最终得到了这个工作,我想我应该分享我的解决方案。

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    使用NuGet包下载JSON-js json2和Json.NET。安装NuGet包的步骤:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... 通过jQuery发布JSON数据到asp.net MVC 4控制器操作。

    (1)在Visual Studio中,到>网站管理NuGet包…

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.通过jQuery发布JSON数据到asp.net MVC 4控制器操作。

    (2)在搜索栏中输入json(或类似的东西),找到json -js json2和Json.NET。双击它们将把包安装到当前项目中。

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

    (3) NuGet会自动将json文件放在~/Scripts/json2.min中。项目目录中的js。找到json2.min。js文件并将其拖放到网站的头部。注意:有关安装.js (javascript)文件的说明,请阅读此解决方案。

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    创建包含所需参数的类对象。您将使用它访问API控制器中的参数。示例代码:

    Public Class PostMessageObj
    
    Private _body As String
    Public Property body As String
        Get
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    
    
    Private _id As String
    Public Property id As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
    
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    然后,我们设置实际的MVC 4 Web API控制器,我们将使用它作为POST操作。在其中,我们将使用Json。在字符串对象被发布时反序列化。记住要使用适当的名称空间。继续前面的示例,下面是我的代码:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    
    Dim body As String = t.body
    Dim i As String = t.id
    
    End Sub
    
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    现在我们已经设置了API控制器来接收经过stringified的JSON对象,我们可以使用$.ajax从客户端免费调用POST操作;继续前面的示例,下面是我的代码(适当地替换localhost+rootpath):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    }
    var jsondata = JSON.stringify(tempdata)
    $.ajax({
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'
    });
    

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.

如您所见,我们正在构建JSON对象,将其转换为字符串,将其作为单个参数传递,然后通过JSON重新构建。净框架。我没有在API控制器中包含返回值,所以我只是在success()函数中放置了一个任意的字符串值。


Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

这是在Visual Studio 2010中使用ASP完成的。NET 4.0,WebForms,VB。NET和MVC 4 Web API控制器。对于任何在将MVC 4 Web API与VS2010集成方面有困难的人,您可以下载该补丁使之成为可能。你可以从微软的下载中心下载。

Here are some additional references which helped (mostly in C#):

以下是一些帮助(主要是在c#中):

#4


1  

//simple json object in asp.net mvc

// asp.net mvc中的简单json对象。

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({    url: 'test/[ControllerName]',
                        type: "POST",
                        data: model,
                        success: function (res) {
                            if (res != null) {
                                alert("done.");
                            }
                        },
                        error: function (res) {

                        }
                    });


//model in c#
public class MyModel
{
 public string Id {get; set;}
 public string Name {get; set;}
}

//controller in asp.net mvc


public ActionResult test(MyModel model)
{
 //now data in your model 
}

#5


0  

Some months ago I ran into an odd situation where I also needed to send some Json-formatted date back to my controller. Here's what I came up with after pulling my hair out:

几个月前,我遇到了一个奇怪的情况,我还需要发送一些json格式的日期回到我的控制器。以下是我拔下头发后想到的:

My class looks like this :

我的班级看起来是这样的:

public class NodeDate
{
    public string nodedate { get; set; }
}
public class NodeList1
{
    public List<NodeDate> nodedatelist { get; set; }
}

and my c# code as follows :

我的c#代码如下:

        public string getTradeContribs(string Id, string nodedates)
    {            
        //nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}";  // sample Json format
        System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1));
        string thisDate = "";
        foreach (var date in nodes.nodedatelist)
        {  // iterate through if needed...
            thisDate = date.nodedate;
        }   
    }

and so I was able to Deserialize my nodedates Json object parameter in the "nodes" object; naturally of course using the class "NodeList1" to make it work.

因此,我可以在“节点”对象中反序列化nodedates Json对象参数;当然,要使用“NodeList1”类来实现它。

I hope this helps.... Bob

我希望这有助于....鲍勃

#6


0  

Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...

我的客户端(一个cshtml文件)使用数据属性来显示网格(现在使用非常棒的infragementcontrol)。一旦用户点击了行,我就捕获了行事件和与该记录相关的日期,以便返回服务器并对交易进行额外的服务器端请求,等等。

The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :

DataTables def开始时是这样的(留下了很多东西),点击事件如下所示,我将其推入Json对象:

    oTablePf = $('#pftable').dataTable({         // INIT CODE
             "aaData": PfJsonData,
             'aoColumnDefs': [                     
                { "sTitle": "Pf Id", "aTargets": [0] },
                { "sClass": "**td_nodedate**", "aTargets": [3] }
              ]
              });

   $("#pftable").delegate("tbody tr", "click", function (event) {   // ROW CLICK EVT!! 

        var rownum = $(this).index(); 
        var thisPfId = $(this).find('.td_pfid').text();  // Find Port Id and Node Date
        var thisDate = $(this).find('.td_nodedate').text();

         //INIT JSON DATA
        var nodeDatesJson = {
            "nodedatelist":[]
        };

         // omitting some code here...
         var dateArry = thisDate.split("/");
         var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];

         nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });

           getTradeContribs(thisPfId, nodeDatesJson);     // GET TRADE CONTRIBUTIONS 
    });

#1


23  

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

问题在于数据类型和数据参数的格式。我刚刚在一个沙箱里测试了这个,下面的工作如下:

C#

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>

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.

在发送文本时,要特别注意数据,您需要发送一个与参数名称匹配的变量。它并不漂亮,但是它会让你得到你梦寐以求的未格式化的字符串。

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

运行时,jsonOfLog在服务器函数中是这样的:

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

The HTTP POST header:

HTTP POST头:

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

The HTTP POST body:

HTTP POST的身体:

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

The response header:

响应头:

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==?=

The response body:

响应身体:

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

#2


2  

I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?

如果你参考这篇文章,你会找到你的答案:将JSON反序列化为c#动态对象?

There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.

实现你想要的东西有很多种方法。System.Web.Helpers。Json方法(一些答案)似乎是最简单的。

#3


2  

VB.NET VERSION

Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

好了,我花了几个小时寻找一个可行的方法,将多个参数发布到MVC 4 WEB API中,但我发现的大部分内容要么是“GET”操作,要么就是干脆不工作。然而,我最终得到了这个工作,我想我应该分享我的解决方案。

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    使用NuGet包下载JSON-js json2和Json.NET。安装NuGet包的步骤:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... 通过jQuery发布JSON数据到asp.net MVC 4控制器操作。

    (1)在Visual Studio中,到>网站管理NuGet包…

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.通过jQuery发布JSON数据到asp.net MVC 4控制器操作。

    (2)在搜索栏中输入json(或类似的东西),找到json -js json2和Json.NET。双击它们将把包安装到当前项目中。

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

    (3) NuGet会自动将json文件放在~/Scripts/json2.min中。项目目录中的js。找到json2.min。js文件并将其拖放到网站的头部。注意:有关安装.js (javascript)文件的说明,请阅读此解决方案。

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    创建包含所需参数的类对象。您将使用它访问API控制器中的参数。示例代码:

    Public Class PostMessageObj
    
    Private _body As String
    Public Property body As String
        Get
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    
    
    Private _id As String
    Public Property id As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
    
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    然后,我们设置实际的MVC 4 Web API控制器,我们将使用它作为POST操作。在其中,我们将使用Json。在字符串对象被发布时反序列化。记住要使用适当的名称空间。继续前面的示例,下面是我的代码:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    
    Dim body As String = t.body
    Dim i As String = t.id
    
    End Sub
    
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    现在我们已经设置了API控制器来接收经过stringified的JSON对象,我们可以使用$.ajax从客户端免费调用POST操作;继续前面的示例,下面是我的代码(适当地替换localhost+rootpath):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    }
    var jsondata = JSON.stringify(tempdata)
    $.ajax({
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'
    });
    

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.

如您所见,我们正在构建JSON对象,将其转换为字符串,将其作为单个参数传递,然后通过JSON重新构建。净框架。我没有在API控制器中包含返回值,所以我只是在success()函数中放置了一个任意的字符串值。


Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

这是在Visual Studio 2010中使用ASP完成的。NET 4.0,WebForms,VB。NET和MVC 4 Web API控制器。对于任何在将MVC 4 Web API与VS2010集成方面有困难的人,您可以下载该补丁使之成为可能。你可以从微软的下载中心下载。

Here are some additional references which helped (mostly in C#):

以下是一些帮助(主要是在c#中):

#4


1  

//simple json object in asp.net mvc

// asp.net mvc中的简单json对象。

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({    url: 'test/[ControllerName]',
                        type: "POST",
                        data: model,
                        success: function (res) {
                            if (res != null) {
                                alert("done.");
                            }
                        },
                        error: function (res) {

                        }
                    });


//model in c#
public class MyModel
{
 public string Id {get; set;}
 public string Name {get; set;}
}

//controller in asp.net mvc


public ActionResult test(MyModel model)
{
 //now data in your model 
}

#5


0  

Some months ago I ran into an odd situation where I also needed to send some Json-formatted date back to my controller. Here's what I came up with after pulling my hair out:

几个月前,我遇到了一个奇怪的情况,我还需要发送一些json格式的日期回到我的控制器。以下是我拔下头发后想到的:

My class looks like this :

我的班级看起来是这样的:

public class NodeDate
{
    public string nodedate { get; set; }
}
public class NodeList1
{
    public List<NodeDate> nodedatelist { get; set; }
}

and my c# code as follows :

我的c#代码如下:

        public string getTradeContribs(string Id, string nodedates)
    {            
        //nodedates = @"{""nodedatelist"":[{""nodedate"":""01/21/2012""},{""nodedate"":""01/22/2012""}]}";  // sample Json format
        System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
        NodeList1 nodes = (NodeList1)ser.Deserialize(nodedates, typeof(NodeList1));
        string thisDate = "";
        foreach (var date in nodes.nodedatelist)
        {  // iterate through if needed...
            thisDate = date.nodedate;
        }   
    }

and so I was able to Deserialize my nodedates Json object parameter in the "nodes" object; naturally of course using the class "NodeList1" to make it work.

因此,我可以在“节点”对象中反序列化nodedates Json对象参数;当然,要使用“NodeList1”类来实现它。

I hope this helps.... Bob

我希望这有助于....鲍勃

#6


0  

Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...

我的客户端(一个cshtml文件)使用数据属性来显示网格(现在使用非常棒的infragementcontrol)。一旦用户点击了行,我就捕获了行事件和与该记录相关的日期,以便返回服务器并对交易进行额外的服务器端请求,等等。

The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :

DataTables def开始时是这样的(留下了很多东西),点击事件如下所示,我将其推入Json对象:

    oTablePf = $('#pftable').dataTable({         // INIT CODE
             "aaData": PfJsonData,
             'aoColumnDefs': [                     
                { "sTitle": "Pf Id", "aTargets": [0] },
                { "sClass": "**td_nodedate**", "aTargets": [3] }
              ]
              });

   $("#pftable").delegate("tbody tr", "click", function (event) {   // ROW CLICK EVT!! 

        var rownum = $(this).index(); 
        var thisPfId = $(this).find('.td_pfid').text();  // Find Port Id and Node Date
        var thisDate = $(this).find('.td_nodedate').text();

         //INIT JSON DATA
        var nodeDatesJson = {
            "nodedatelist":[]
        };

         // omitting some code here...
         var dateArry = thisDate.split("/");
         var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];

         nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });

           getTradeContribs(thisPfId, nodeDatesJson);     // GET TRADE CONTRIBUTIONS 
    });