Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post Javascript array to C# list of tuples ?

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.

like image 405
Rian Mostert Avatar asked Jan 17 '18 12:01

Rian Mostert


1 Answers

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; }
}
like image 51
Mihai Alexandru-Ionut Avatar answered Oct 16 '22 04:10

Mihai Alexandru-Ionut