1

I have a little jquery code:

     //foreach the inputs
         json.push({
                 Var1: $(this).attr("id"),
                 Var2: filename,
                 Var3: hash_name
              });
      //end foreach

      $.post(url, {test: json}, function(){}, 'json');

We suppose that json has 3 objects (after browsing 3 inputs and getting their values). and the structure in MVC3 model:

public struct Simple
   {
      public string Var1 {
         get;
         set;
      }

      public string Var2{
         get;
         set;
      }

      public string Var3{
         get;
         set;
      }

      public bool Var4 {
         get;
         set;
      }
   }

and the controller:

 [HttpPost]
 public ActionResult Test( List<Simple> test) {
   ...
 }

the List<Simple> returns 3 elements (here is correct) but the values for all properties are null (except Var4 which is false).

Why ?

2 Answers 2

1

If it's the ModelBinding that you wanna do, then there's a bit more of work required. But if you simply want the json array on the server side, well here's a quick hack. Download System.Json (you can do it via NuGet). On the client side don't send a JSON object, because this would require a completely different approach. Instead stringify it before hand

    $(document).ready(function () {
        var json = [

            {
                Name: "John Doe",
                Age: 34
            }];
        var str = JSON.stringify(json);
        console.log(str);
        $.ajax({
            url: '/mycontroller/LoadJson',
            data: { values: str },
            type: 'POST',                
            success: function (data) {                   
              //do something
            }
        });
    });

And on the server side you can use JsonValue.Parse into a dynamic object (which then you could "translate" to one of your custom objects)

    [HttpPost]
    public ActionResult LoadJson(FormCollection collection)
    {
        dynamic values = JsonValue.Parse(collection["values"]);       
        for(int i = 0; i < values.Count; i++)
        {
            var _output = string.Format("My name is {0} and I'm {1} of age", values[i].Name, values[i].Age);
            Console.WriteLine(_output);
        }
        return RedirectToAction("Index");
    }

Here's a lengthier post about dynamic Json parsing http://www.west-wind.com/weblog/posts/2012/Mar/19/Dynamic-JSON-Parsing-in-NET-with-JsonValue

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

1

the name should be like this (the Json key value)

test[0].Var1
test[0].Var2
test[0].Var3

test[1].Var1
.....

Or

[0].Var1
[0].Var2
[0].Var3
......

the idea the server can't relate what are the properties that make each object , so the number is just for grouping

and Var4 is false because the model binder instantiated it with its default value , it didn't read any value from the form


Ex

Javascript

json.push({
                 'test[0].Var1': $(this).attr("id"),
                 'test[0].Var1': filename,
                 'test[0].Var1': hash_name
              });

you should increment the 0 for each object

the name test in the JavaScript must match the parameter name for the action method

4 Comments

Can you provide me an example to use key value in javascript ? there are the problem, not in controller
like 'test['+i+'].Var1' doesn't work ! JS compiler expects : at first appareance of + symbol
check the data structure using firebug that you send , and it should work , you still get the error from your second comment ?
you can always construct your keys string outside of the object creation code then pass the string that you made when creating the object key Ex var1 : $(this).attr("id")

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.