MVC - How to ModelBind a list an objects with this unusual post data format?

最后都变了- 提交于 2019-12-10 18:16:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!