问题
Normally when you ModelBind a list of objects with MVC, the action looks like so:
public ActionResult Hello(List<DocumentViewModel> viewModels)
{
And the Post data looks something like:
[0].Id 1
[0].Name Bob
[1].Id 2
[1].Name Jane
But, how could I get the following post data to work?
0[Id] 1
0[Name] Bob
1[Id] 2
1[Name] Jane
The Post data is being provided by Kendo UI, so I don't imagine I have much flexibility to change it.
Update Thanks Petur for the answer. To expand on his answer, this function:
common.MvcSerializeArray = function (array, prefix) {
var result = {};
if (!prefix) {
prefix = '';
}
if (array) {
for (var i = 0; i < array.length; i++) {
if ($.isPlainObject(array[i])) {
for (var property in array[i]) {
result[prefix + "[" + i + "]." + property] = array[i][property];
}
} else {
result[prefix + "[" + i + "]"] = array[i];
}
}
}
return result;
};
should wrap arrays before being returned to Kendo's Data method:
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read
.Action("PickerDocuments", "DocumentRepository")
.Data(@<text>function(e) { return MyApp.Common.MvcSerializeArray(@Html.Raw(Json.Encode(Model))); }</text>)))
And voila, I get post data MVC ModelBinds with ease:
[0].Id 1
[0].Name Bob
[1].Id 2
[1].Name Jane
回答1:
You cannot change it but you can add the desired format by sending addiotional parameters like explained here for the Ajax Grid. Same approach is used in this code library (you can get the magic function inside of the code, it is used to send the multi-select values)
来源:https://stackoverflow.com/questions/18853779/mvc-how-to-modelbind-a-list-an-objects-with-this-unusual-post-data-format