0

I want to do the following.

  1. Pass a complex json object in a hidden input variable
  2. Get that hidden variable through the form collection object.
  3. Convert that hidden text value to a dynamic object which I can loop through to get the data from it

So I think the first two items above I can do.

  1. $("#hiddenVariableID").val(JSON.stringify(data));
  2. Have a parameter called FormCollection collection in the MVC controller. Then get the value the following way String data = collection.Get("hiddenVariableID");
  3. ?? Not sure how to do this.

The data I'm passing is an array of objects. The objects are never the same so that is why I need to convert the results in some type of dynamic object that I can loop through.

I can't do an ajax call to do this because I want to stream down the data passed in the hidden variable. So it has to be through a form submission.

Thank you, -Tesh

1 Answer 1

1

You can at that point use some JSON parser to convert between the string and a JSON object you can access dynamically. There are many JSON parsers out there, the code below shows how it can be done with two of them: the JavaScriptSerializer (part of the .NET Framework), and the JSON.NET (a non-MS library, but which IMO is really good).

public static void Test()
{
    string JSON = @"[
        {'name':'Scooby Doo', 'age':10},
        {'name':'Shaggy', 'age':18},
        {'name':'Daphne', 'age':19},
        {'name':'Fred', 'age':19},
        {'name':'Velma', 'age':20}
    ]".Replace('\'', '\"');

    Console.WriteLine("Using JavaScriptSerializer");
    JavaScriptSerializer jss = new JavaScriptSerializer();
    object[] o = jss.DeserializeObject(JSON) as object[];
    foreach (Dictionary<string, object> person in o)
    {
        Console.WriteLine("{0} - {1}", person["name"], person["age"]);
    }

    Console.WriteLine();
    Console.WriteLine("Using JSON.NET (Newtonsoft.Json) parser");
    JArray ja = JArray.Parse(JSON);
    foreach (var person in ja)
    {
        Console.WriteLine("{0} - {1}", person["name"].ToObject<string>(), person["age"].ToObject<int>());
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.