MVC4 ModelState属性名称为JSON或Array

时间:2013-12-30 20:50:03

标签: javascript arrays asp.net-mvc-4

我正在使用一个复杂的对象图,序列化为JSON,MVC4 / jQuery / Sammy / Rivets用于SPA功能。

我有一个对象图,在序列化为JSON时看起来有点像这样(显然是模拟的):

model = 
    { 
        Name: "Me",
        Age: 22,
        Hobbies: 
            [ 
                { Name: "Biking", IsActive: true },
                { Name: "Programming", IsActive: true } 
            ]
    }

在我需要Unobtrusive验证之前,一切都运行良好,因为我的爱好在SlickGrid中,我自己管理所有数据。为了解决这个问题,我将模型旁边的JSON返回给我的ModelState。

return JSON(new { model = model, modelState = this.ModelState });

从那里我打算遍历modelState并使用一些自定义函数将错误分配到正确的位置,但是有一个问题。

ModelState如下所示:

"Name",
"Age",
"Hobbies[0].Name",
"Hobbies[0].IsActive",
"Hobbies[1].Name",
"Hobbies[1].IsActive"

我需要将[0]分成对象,将[1]分成自己的对象,这样我就能顺利得到这些值。当我开始考虑第三级复杂对象数组时,这让我感到困惑。

解决方案:

var ModelStateConverter = function ($, module) {
    module = module || {};

    // Convert The ModelState form style object to a standard JS object structure.
    module.toObject = function (modelState) {
        var ModelState = {};

        $.each(modelState, function (key, value) {
            AssignValuesToObjectStore(key, ModelState, value);
        });

        return ModelState;
    }

    // item is the full identifier ex. "Hobbies[0].Name"
    // store is the object we are going to throw arrays, objects, and values into.
    // value is the error message we want to get in the right place.
    // index is an internal processing parameter for arrays only, setting it's value has no effect.
    function AssignValuesToObjectStore(item, store, value, index) {
        var periodMatch = item.match(/[\.]/);

        if (periodMatch === null) {
            if (Array.isArray(store)) {
                if (store[index] === undefined) {
                    store[index] = {};
                }

                store[index][item] = value;
            }
            else {
                 store[item] = value;
            }
        }
        else {
            // This wasn't a simple property or end of chain.

            var currentProperty = item.slice(0, periodMatch.index); // Get our property name up to the first period.
            var container = {}; // We assume we are dealing with an object unless proven to be an array.
            var arrayIndex; // This is irrelevant unless we have an array.

            if (currentProperty.slice(-1, currentProperty.length) === "]") {

                // We are dealing with an array! Hoo Ray?!
                arrayIndex = parseInt(currentProperty.slice(currentProperty.indexOf("[") + 1, currentProperty.indexOf("]")));

                currentProperty = currentProperty.slice(0, currentProperty.indexOf("[")); // remove the indexer ex. [0] so we are left with the real name

                container = []; // We know we need an array instead;
            }

            if (store[currentProperty] === undefined) {
                store[currentProperty] = container; // If this property isn't already created, then do so now.
            }

            //Recurseive nature here.
            AssignValuesToObjectStore(item.slice(periodMatch.index + 1, item.length), store[currentProperty], value, arrayIndex);
        }
    }

    return module;
}($, ModelStateConverter);

您可以通过以下方式致电:

ModelStateConverter.toObject(data.modelState);

其中data.modelState被假定为服务器的ModelState。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用JSON.NET或类JavaScriptSerializer等库来序列化ModelState。