2

I am trying to learn ASP.Net MVC and I wanted to post array of JSON objects to the server and sent it back to the client side. Everything is fine when I use Postman, but it doesn't work on actual web page. I think the problem is either with jQuery code that posts the array or ASP.Net code that is not able to parse the array.

enter image description here

Here is my controller code:

[System.Web.Mvc.HttpPost]
public ActionResult GetResult(List<Table> list)
{
    return Json(list);
}

Here is my object declaration:

public class Table
{
    public int Id { get; set; }
    public String Question { get; set; }
    public int Answer { get; set; }
}

Here is jQuery code that posts the data:

$.post("./GetResult", JSON.stringify(tableData), function (data, status) { alert(status); }, "json");

and tableData is an Array of JSON like this:

[
    {
        "Id": 500,
        "Question": "where are you from",
        "Answer": 2
    },
    {
        "Id": 501,
        "Question": "how old are you",
        "Answer": 1
    },
    {
        "Id": 502,
        "Question": "what is your first car",
        "Answer": 2
    },
    {
        "Id": 503,
        "Question": "do you have kids",
        "Answer": 1
    }
]

Also, I can see that my code goes through the post controller but it is empty or null. enter image description here

Here is the link of my csHTML file.

Node.JS
  • 1,042
  • 6
  • 44
  • 114
  • possible duplicate of [Post Array as JSON to MVC Controller](http://stackoverflow.com/questions/10007722/post-array-as-json-to-mvc-controller) – wf4 Mar 10 '15 at 20:54

3 Answers3

1

There is no need to JSON.stringify in your $.post call. Let jQuery handle that for you.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

Try to specify content-type in your request:

$.ajax({
  url: "./GetResult",
  type: "POST",
  data: JSON.stringify(tableData),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (data, status) { alert(status); }
})
Grant
  • 2,295
  • 3
  • 14
  • 13
0
$.post("./GetResult", {list:tableData},
    function (data, status) 
    { 
        alert(status); 
    }
, "json");

Json never passed object.

using Newtonsoft.Json;
[HttpPost]
Public ActionResult GetResult(string list)
{
    var obj = JsonConvert.DeserializeObject<List<Table>>(strStatus);
    return Json(list)
}

or

$.ajax({
  url: "./GetResult",
  type: "POST",
  data: JSON.stringify(tableData),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (data, status) { alert(status); }
})
Nimesh Gami
  • 361
  • 1
  • 2
  • 18