Snake Eyes
Snake Eyes

Reputation: 16764

Parse JSON object to pass parameters to generic list in C# MVC3 controller via ajax

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 ?

Upvotes: 1

Views: 5305

Answers (2)

coffeeyesplease
coffeeyesplease

Reputation: 1028

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

Upvotes: 1

Nadeem Khedr
Nadeem Khedr

Reputation: 5313

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

Upvotes: 1

Related Questions