JS Object To C# ASP.Net ModelBind

之前做项目的时候发现,Jquery自带的Form 序列化函数。与asp.net 里边的Modelbinding格式不匹配,所以写了一个可以把前端的Object对象序列化成ModelBinding认识的数据格式的函数

//序列化对象
var serializedObj = function (obj) {
    var arr = [];
    recursiveSerialization(obj, arr, '');
    return arr.join('&');
}
var recursiveSerialization = function (obj, arr, head) {
    if (obj == '' || typeof obj == 'undefined') {
        return;
    }
    if (Array.isArray(obj)) {
        for (var i = 0; i < obj.length; i++) {
            var newhead = head + '[' + i + ']';
            recursiveSerialization(obj[i], arr, newhead);
        }
    }
    else if (typeof obj == 'number' || typeof obj == 'boolean' || typeof obj == 'string') {
        arr.push(head + '=' + obj + '');
    } else {
        for (var key in obj) {
            var newhead
            if (head == "") {
                newhead = key;
            } else {
                newhead = head + '.' + key;
            }
            recursiveSerialization(obj[key], arr, newhead)
        }
    }
}
posted @ 2018-06-01 15:07  连程  阅读(150)  评论(0编辑  收藏  举报