Model binding issues with Kendo objects with complex child properties

試著忘記壹切 提交于 2020-01-05 03:59:08

问题


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:


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 :)



来源:https://stackoverflow.com/questions/18149982/model-binding-issues-with-kendo-objects-with-complex-child-properties

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