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.
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.
Share Improve this question edited Jan 17, 2018 at 13:26 Mihai Alexandru-Ionut 48.5k14 gold badges105 silver badges132 bronze badges asked Jan 17, 2018 at 12:34 Rian MostertRian Mostert 7141 gold badge7 silver badges19 bronze badges 3- 2 Is there a reason you can't use a proper class? This isn't really what Tuples were designed for. – fdomn-m Commented Jan 17, 2018 at 12:36
- 1 @freedomn-m No reason, just curiosity. – Rian Mostert Commented Jan 17, 2018 at 12:44
-
@freedomn-m, yes, tuples aren't designed for this. Also, model binding cannot map to one
Tuple
. – Mihai Alexandru-Ionut Commented Jan 17, 2018 at 13:23
1 Answer
Reset to default 6You 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; }
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744762109a4592233.html
评论列表(0条)