I was wondering if anyone knew how to pass a Javascript array of objects to a MVC action method accepting an array of tuples.
Example:
The Javascript:
var objectArray =
[
{ id: 1, value: "one" },
{ id: 2, value: "two" }
];
$.post('test',objectArray);
The MVC controller action:
public JsonResult Test((int id, string value)[] objectArray)
{
return Json(objectArray != null);
}
Unfortunately the example I've given always returns false as the objectArray in the C# code is null.
You cannot do this because like the error says: a tuple has no parameterless constructor, so the model binder can't instantiate it.
Also, you can read more about Model Binding.
One of the phrases said this:
In order for binding to happen the class must have a public default constructor and member to be bound must be public writable properties. When model binding happens the class will only be instantiated using the public default constructor, then the properties can be set.
You can use another approach:
First of all, you have to send the given array using JSON.stringify
method.
JSON.stringify()
turns a javascript object to json
text and stores it in a string
.
AJAX
objectArray = JSON.stringify({ 'objectArray': objectArray });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'test',
data: objectArray ,
success: function () {
}
});
In your server-side method you have to pass a list of objects as parameter.
[HttpPost]
public void PassThings(List<Thing> objectArray )
{
}
public class Thing
{
public int Id { get; set; }
public string Value { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With