Model binding issues with Kendo objects with compl

2019-07-16 06:00发布

I have a Kendo UI grid which allows me to post multiple changes to the server. The model that is bound to the grid contains a list of a complex type. Here it is (simplified):

public class User
{    
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Role> Roles { get; set; }        
}

To update the changes on the server I have a method with the following signature in my controller:

public ActionResult UpdateUtilisateurs([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<User> users)

The users collection gets filled correctly, however the Roles list is empty. I have ensured using Firebug that the data was actually serialized back and forth. Here's the POST when I update 1 row just before getting to the controller:

filter  
group   
models[0].ID                     16
models[0].Name                   Amir Majic
models[0].Roles[0][Code]         dbadmin
models[0].Roles[0][Description]  Database Administrator
models[0].Roles[0][ID]           33
sort

So the data seems OK (except maybe for the missing dot in the Rolesproperty?). So must I change method signature? Do I have to create a custom model binder (though I guess this is a fairly common scenario)?

1条回答
爷的心禁止访问
2楼-- · 2019-07-16 06:04

Had the exact same problem. The problem is with the brackets of the child properties (models[0].Roles[0][Code] instead of models[0].Roles[0].Code). You will need a parse function before sending the data to the server (or update the default model binder).

Kendo support sent me a solution:

In the Ajax DataSource:

.Update(update => update.Action("Update", "Controller").Data("serialize"))
.Create(create => create.Action("Create", "Controller").Data("serialize"))

Later in the view (or a JS file)

<script>
    function serialize(data) {
        for (var property in data) {
            if ($.isArray(data[property])) {
                serializeArray(property, data[property], data);
            }
        }
    };

    function serializeArray(prefix, array, result) {
        for (var i = 0; i < array.length; i++) {
            for (var property in array[i]) {
                result[prefix + "[" + i + "]." + property] = array[i][property];
            }
        }
    }
</script>

If your plans are to use a grid to edit that collection of complex objects, I'll tell you right now, you will regret your decision. Just a friendly warning to save you a few days of wasted time :)

查看更多
登录 后发表回答