js-Serializer,ajax提交到后台mvc

var saveChanges=[];
saveChanges.push({ID:"1",SCOMPANYCODE:"10000000"})

var serializer = new Serializer();
            var param = serializer.parameterMap(saveChanges, "model");
            $.ajax({
                url: "Biz_CA_YD_YSOtherIncome/SaveData",
                data: param,
                success: function (d) {
                    if (d.Data=="ok") {
                        initGrid(true);
                        //alert("保存成功");
                        utility.showSuccess("保存成功");
                    } else {
                        alert(d.Message);
                    }
                },
                error: function (error) {
                    alert(error.message);
                }
            });
public ActionResult SaveData([Bind(Prefix = "model")]List<SM_COMPANY_YSOTHERINCOME> model)
        {
            string result = "";
            result = bll.SaveData(model);
            if (string.IsNullOrWhiteSpace(result))
            {
                return this.ResponseAjaxResult(new
                {
                    Data = "ok",
                    Message = ""
                });
            }
            else
            {
                return this.ResponseAjaxResult(new
                {
                    Data = "error",
                    Message = result
                });
            }
        }

 

define(["jquery"], function ($) {

    function DataHelper() {
        var tagName = "input";//or textarea
        var propName = "binddatafield";

        this.setFieldName = function (propertyName) {
            propName = propertyName;
        }

        this.setTagName = function (tag) {
            tagName = tag;
        }

        //输入框绑定数据
        this.bindTextBoxField = function (jsonData, $container, byID) {
            $(tagName + "[" + propName + "]", $container).val("");
            var elInput, propEntry;
            if (!jsonData) return;
            var tempPropName = propName;
            if (!!byID)
                propName = "id";
            for (var prop in jsonData) {
                propEntry = jsonData[prop];
                if (typeof propEntry == "object") {
                    var prefix = prop + ".";
                    for (var innerProp in propEntry) {
                        var propValue = propEntry[innerProp];
                        elInput = $(tagName + "[" + propName + "='" + prefix + innerProp + "']", $container);
                        if (elInput.length > 0)
                            elInput.val(propValue);
                    }
                }
                else {
                    elInput = $(tagName + "[" + propName + "='" + prop + "']", $container);
                    if (elInput.length > 0) elInput.val(propEntry);
                }
            }
            this.setFieldName(tempPropName);
        }

        //从输入框生成MVC可以直接解析的参数数据
        this.GetJsonFromInput = function (paramname, $container, byID) {
            var retObj = {};
            var arrInput = $(tagName + "[" + propName + "]", $container);
            var propValue;
            var tempPropName = propName;
            if (!!byID)
                propName = "id";
            arrInput.each(function (index, el) {
                propValue = $(el).attr(propName);
                propValue = paramname + "." + propValue;
                retObj[propValue] = $(el).val();
            });
            this.setFieldName(tempPropName);
            return retObj;
        }

    }

    return new DataHelper();
});


function Serializer() {
    var serializeItem = function (result, item, prefix) {
        var value,
            key;

        item = convert(item);

        for (var member in item) {
            key = prefix + member;
            value = item[member];

            if ($.isPlainObject(value)) {
                flatten(result, value, key);
            } else {
                result[key] = value;
            }
        }
    };

    var convert = function (values) {
        for (var key in values) {
            var value = values[key];

            if (value instanceof Date) {
                values[key] = kendo.format("{0:G}", value);
            }

            if (typeof value === "number") {
                value = value.toString();
            }

            if (value == null) {
                delete values[key];
            }

            if ($.isPlainObject(value)) {
                convert(value);
            }
        }
        return values;
    }

    var flatten = function (result, value, prefix) {
        for (var key in value) {
            if ($.isPlainObject(value[key])) {
                flatten(result, value[key], prefix ? prefix + "." + key : key);
            } else {
                result[prefix ? prefix + "." + key : key] = value[key];
            }
        }
    }

    this.parameterMap = function (models, prefix) {
        var result = {};
        if (models) {
            if ($.isPlainObject(models)) {
                serializeItem(result, models, prefix + ".");
            } else {
                for (var i = 0; i < models.length; i++) {
                    serializeItem(result, models[i], prefix + "[" + i + "].");
                }
            }

        } else if (options) {
            serializeItem(result, options, "");
        }

        return result;
    }

    this.collect = function () {
        var ret = {};
        var len = arguments.length;
        for (var i = 0; i < len; i++) {
            for (var p in arguments[i]) {
                if (arguments[i].hasOwnProperty(p)) {
                    ret[p] = arguments[i][p];
                }
            }
        }
        return ret;
    }
}
/**
 *  usage: "12,13,23".contains("12")  //true
 */
String.prototype.contains = function (str) {
    var arr = this.split(',');
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === str)
            return true;
    }
    return false;
}
/**
 *  去除尾部字符串
 */
String.prototype.trimEnd = function (endOfStr) {
    if (typeof endOfStr != "string") { return this; }
    if (this.substr(this.length - endOfStr.length, endOfStr.length) != endOfStr) {
        return this;
    }
    return this.substr(0, this.length - endOfStr.length);
};
/**
 *  查找数组中是否存在相似对象并返回,相似对象 compObj中出现的属性和值在被查找对象中必须存在并相同。
 */
Array.prototype.getSimiliar = function (compObj,createNew) {
    if (this.length == 0)
        return null;
    if (!!createNew) {
        return $.grep(this, function (el, i) {
            return compareSimiliar(el, compObj);
        });
    } else {
        var retObj=null;
        $.each(this, function (i, el) {
            var beSimiliar = compareSimiliar(el,compObj);
            if (beSimiliar) {
                retObj = el;
                return false;
            }
        })
        return retObj;
    }
    function compareSimiliar(el,obj) {
        var beSimiliar = true;
        for (var prop in obj) {
            if (el.hasOwnProperty(prop) == false) {
                beSimiliar = false;
                break;
            }
            if (el[prop] !== obj[prop]) {
                beSimiliar = false;
                break;
            }
        }
        return beSimiliar;
    }
}
/**
 *  克隆数组,数组元素可以是基本类型或对象。
 */
Array.prototype.clone = function () {
    var arr = [];
    $.each(this, function (i, el) {
        if (typeof el == "object") {
            arr.push($.extend(true, {}, el));
        } else {
            arr.push(el);
        }
    })
    return arr;
}

/*
 *   数组元素去重
 */
Array.prototype.unique = function () {
    var res = [], hash = {};
    for (var i = 0, elem; (elem = this[i]) != null; i++) {
        if (!hash[elem]) {
            res.push(elem);
            hash[elem] = true;
        }
    }
    return res;
}

 

posted @ 2015-11-06 17:58  wjl910  阅读(155)  评论(0)    收藏  举报