Post Json Array to MVC Controller

Post JSON array to mvc controller

There are lots of issues with your code. Let's start with the markup. You have a table and inside each row of this table you are including hidden fields. Except that you have hardcoded the id attribute of those hidden elements meaning that you could potentially end up with multiple elements with the same id in your markup which results in invalid markup.

So let's start by fixing your markup first:

@foreach (var t in Model.Types.ToList())
{
<tr>
<td>
<input type="hidden" value="@t.TransID" name="TransID" />
<input type="hidden" value="@t.ItemID" name="ItemID" />
<input type="hidden" value="@t.TypeID" name="TypeID" />
</td>
</tr>
}

Alright, now you have valid markup. Now let's move on to the javascript event which will be triggered when some submitTest button is clicked. If this is the submit button of the form I would recommend you subscribing to the .submit event of the form instead of the .click event of its submit button. The reason for this is because a form could be submitted for example if the user presses the Enter key while the focus is inside some input field. In this case your click event won't be triggered.

So:

$(document).ready(function () {
$('form').submit(function () {
// code to follow

return false;
});
});

Alright, next comes the part where you need to harvest the values of the hidden elements which are inside the table and put them into a javascript object that we will subsequently JSON serialize and send as part of the AJAX request to the server.

Let's go ahead:

var parameters = [];
// TODO: maybe you want to assign an unique id to your table element
$('table tr').each(function() {
var td = $('td', this);
parameters.push({
transId: $('input[name="TransID"]', td).val(),
itemId: $('input[name="ItemID"]', td).val(),
typeId: $('input[name="TypeID"]', td).val()
});
});

So far we've filled our parameters, let's send them to the server now:

$.ajax({
url: this.action,
type: this.method,
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
success: function (result) {
// ...
},
error: function (request) {
// ...
}
});

Now let's move on to the server side. As always we start by defining a view model:

public class MyViewModel
{
public string TransID { get; set; }
public string ItemID { get; set; }
public string TypeID { get; set; }
}

and a controller action that will take a collection of this model:

[HttpPost]
public ActionResult Update(IList<MyViewModel> model)
{
...
}

And here's the final client side code:

$(function() {
$('form').submit(function () {
if ($(this).valid()) {
var parameters = [];
// TODO: maybe you want to assign an unique id to your table element
$('table tr').each(function() {
var td = $('td', this);
parameters.push({
transId: $('input[name="TransID"]', td).val(),
itemId: $('input[name="ItemID"]', td).val(),
typeId: $('input[name="TypeID"]', td).val()
});
});

$.ajax({
url: this.action,
type: this.method,
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
success: function (result) {
// ...
},
error: function (request) {
// ...
}
});
}
return false;
});
});

Obviously if your view model is different (you haven't shown it in your question) you might need to adapt the code so that it matches your structure, otherwise the default model binder won't be able to deserialize the JSON back.

How to pass a json array of type object to MVC controller class

There are two ways to pass the JS object as List<T> collection using AJAX:

1) Put JSON.stringify with the object itself and set traditional: true option, only single parameter should be set:

$.ajax({
url: '/KPIReportAdmin/SaveDashboard',
type: "POST",
dataType: "json",
contentType: "application/json",
traditional: true,
data: JSON.stringify(dashboards),
success: function (result)
{

},
error: function (result) {
alert("Failed");
}
});

2) Pass the raw object without stringify-ing it by using $.param() function with traditional: true option:

$.ajax({
url: '/KPIReportAdmin/SaveDashboard',
type: "POST",
dataType: "json",
data: $.param({ dashboards: dashboards }, true),
success: function (result)
{

},
error: function (result) {
alert("Failed");
}
});

The exception occurred because you're passing a JS object which containing JSON string with data: { dashboards: JSON.stringify(dashboards) } and controller action method doesn't know how to resolve it into List<T> collection object as parameter.

Related issue:

Invalid JSON primitive: object

How to send JSON Array to an ASP.NET MVC Controller

Try the following:

$.ajax({
type: "POST",
url: "./charts/SaveViewToDatabase",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(jsondata),
success: function (result) {
if (result.success) {
alert("Save View successful!");
} else {
alert("Duplicate View already exist. Not save!");
}
},
error: function () {
alert("No market, load type & region is selected!");
}
});

See added contentType and JSON.stringify into data attribute.

Send Json Array to MVC Controller brings Empty Models?

Your JSON data seems to be one level above JSItem.

Change your controller action to RootObject and see.

[HttpPost]
public JsonResult getCartFromClient(List<RootObject> data)
{
return view();
}

if you don't want to do this, then send the JSOn as Stephen Muecke suggested in the comments, for it to be deserialized as List<JSItem>

And as to why you see the right count for List<JSItem>, but all null values, the reason is this:

When MVC tries to deserialize this value into the List<JSItem>

"[
{
"JSItem":{"xid":"2","xamount":"1","xprice":"50.00","xname":"BaBy Product 1","xlevel":"0"}
},
{
"JSItem":{"xid":"3","xamount":"1","xprice":"0.00","xname":"BaBy Product 122","xlevel":"0"}
}
]"

MVC is able to recognize that the input is an array of elements with count 2.
So it initialized the List<JSItem> with 2 elements. And it starts newing up JSItem for every item, as part of model binding.

However when it tries to set the properties of this newed up JSItem, it doesn't find any matching fields in the JSON. this is because your JSON is one level above the JSItem. Hence all fields are null.

dont Post JSON array to mvc controller

Your posting back an object with 2 properties so you need a model with those 2 properties

public class MyModel
{
public string City { get; set; }
public int Age { get; set; }
}

and the method needs to be changed to

public JsonResult Create(MyModel model)
{
.... // model will be populated with the values you sent
return Json(...);`
}

and you need to remove the following options from the ajax method

contentType : "application/json",
traditional: true,

Alternatively, you method can be

public JsonResult Create(string city, int age)

but you lose the benefits of model validation

Side note: Always use the Url.Action() method to ensure your url's are correctly generated

url: '@Url.Action("Create", "Category")',  

json Array posting to mvc controller

The Problem is solved & my application is working now properly.
I have just done JSON.stringify() on array elements & not the whole ajax data for posting.

the code is as written below:

 var totaldata =  { data: data, playlistid: parseInt(playlistid), Title: Title };
$.ajax({
type: 'POST',
data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
traditional:true,
url: 'Save',
success: function (data) {

alert("Playlist saved successfully!!");

}
})

Sending JSON from View to Controller ASP.NET MVC gives null values

Some things to try:

  1. Open up your Network tab in the dev console and check out the details of the POST request to make sure that the url is correct and that the JSON being sent is what you expect
  2. Decorate the JsonData class with a [DataContract] attribute, and each property with a [DataMember(Name = "Name")] attribute - to make sure that you don't run into issues with casing (the property names in the class are all capitalized, and your json starts with lower case for each).
  3. It looks like you have an extra set of external [ ] brackets on your generated Json. So while your action is expecting List<JsonData> jsonArray, it is being sent List<List<JsonData> jsonArray>. See how it works removing the outermost square brackets from the json being sent.


Related Topics



Leave a reply



Submit