MVC4 ModelState属性名称为JSON或Array

时间:2021-11-20 10:34:09

I am using a complex object graph serialized to JSON with MVC4/jQuery/Sammy/Rivets for SPA functionality.

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

I have a object graph that looks a bit like this when serialized to JSON (obviously mocked-up):

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

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

Everything works quite well until I need Unobtrusive validation, since my Hobbies are in a SlickGrid and I am managing all the data myself. To handle this I am returning my ModelState with my JSON next to my model.

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

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

From there I intend to iterate through the modelState and assign errors to the right place with some custom function, but there is one problem.

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

ModelState looks like this:

ModelState看起来像这样:

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

I need to separate the [0]'s into an object and [1]'s into their own objects so I can smoothly get the values. This gets confusing for me when I begin to account for a third level of complex object array.

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

Solution:

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

You can call this from:

你可以这样叫:

ModelStateConverter.toObject(data.modelState);

Where data.modelState is assumed to be the ModelState from the server.

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

1 个解决方案

#1


0  

You could try a library like JSON.NET, or the class JavaScriptSerializer, to serialize the ModelState.

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

#1


0  

You could try a library like JSON.NET, or the class JavaScriptSerializer, to serialize the ModelState.

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