devc2 February 2016

MVC controller not accepting multidimensional JSON

I am using ASP.NET 5 RC1 Update1

I have a jquery ajax call that posts JSON data of an html table via a POST to a MVC controller method. However the controller method can't seem to receive this data.

html:

<table  id="datatab"  border="1">
    <tbody>
        <tr role="row" class="odd">
            <td class="sorting_1" style="display: none;">2087971</td>
            <td>1</td>
            <td>1</td>
            <td>aaaa</td>
            <td>John Smith</td>
            <td><input type="text"  name="value1" value="1"></td>
            <td><input type="text"  name="value2" value="2"></td>
            <td><input type="text"  name="value3" value="3"></td>
            <td></td>
         </tr>
        <tr role="row" class="even">
            <td class="sorting_1" style="display: none;">2087972</td>
            <td>2</td>
            <td>2</td>
            <td>bbbb</td>
            <td>Peter Parker</td>
            <td><input type="text"  name="value1" value="4"></td>
            <td><input type="text"  name="value2" value="4"></td>
            <td><input type="text"  name="value3" value="4"></td>
            <td></td>
        </tr>
    </tbody>
</table>
<button id="GetData">Get data</button>

jquery:

<script>
   $("#GetData").click(function (event) {
            debugger;
            event.preventDefault();

            var TableData = new Array();
            $('#datatab tbody tr').each(function (row, tr) {
                TableData[row] = {
                    "Id": $(tr).find('td:eq(0)').text()
                      , "Input1Value": $(tr).find('td:eq(5) input').val()
                   

Answers


Shyju February 2016

The data you want to send looks more like a Collection/Array of Dictionary of String,String.

[{
    "Id": "2087971",
    "Input1Value": "1",
    "Input2Value": "2",
    "Input3Value": "3"
}, {
    "Id": "2087972",
    "Input1Value": "4",
    "Input2Value": "4",
    "Input3Value": "4"
}]

So change your action method parameter type to

[HttpPost]
public IActionResult UpdateData([FromBody] List<Dictionary<string,string>> myData)
{
    // do something with myData;
    return Json(myData);
}

Also, in your ajax call, just send the stringified version of your array as the data property value.

var myData = JSON.stringify(TableData);
$.ajax({
    type: "POST",
    contentType: "application/json; charset=UTF-8",
    url: '@(Url.Action("UpdateData", "MyController"))',
    data: myData,
    success: function (msg) {
          console.log(msg);
    }
});

Post Status

Asked in February 2016
Viewed 1,700 times
Voted 13
Answered 1 times

Search




Leave an answer