6

My controller is returning an object graph to the view in json format like this

return Json(customer);

On the view my json object looks like this

{
    Name: 'Joe',
    Budget: { Amount: 500, Spend: 100 }
}

Which maps correctly to my customer object:

public class Customer 
{
    public string Name {get;set;}
    public Budget Budget{get;set;} 
}

public class Budget  
{
    public decimal Amount{get;set;}    
    public decimal Spend{get;set;} 
}

I want to pass that same json object back to another method on the controller with this signature:

public ActionResult Method(Customer customer)

When I do this customer's name get populated but not the Budget class, which I understand why because the modelbinder is expecting this: {Name:'Joe','Budget.Amount':500,'Budget.Spend': 100}

So I have to options: 1. I can return the json object in the format it wants, but I don't know how because you can't do this:

return Json(new { Budget.Amount= 500})
  1. I can flatten the json object on the client side. Is there plugins or methods to do this?
adriaanp
  • 2,064
  • 2
  • 22
  • 40

3 Answers3

5

Here's a function that convert an object to a flat hash

function flatten(json){
    var nj = {},
        walk = function(j){
            var jp;
            for(var prop in j){
                jp = j[prop];
                if(jp.toString() === "[object Object]"){
                    walk(jp);
                }else{
                    nj[prop] = jp;
                }
            }
        };
    walk(json);
    return nj;
}
Mic
  • 24,812
  • 9
  • 57
  • 70
  • Oh no... you want to flatten the json into a hash? – Mic Feb 05 '10 at 22:03
  • your solution will work, but I will need to have 'Budget.Amount' as the property name, I am currently doing it by passing a prefix variable to the 'walk' function – adriaanp Feb 05 '10 at 22:33
  • About the bad practice... I don't know your constraints server side, but yeah... it looks like a receipt for troubles. – Mic Feb 05 '10 at 22:58
1

Protovis has a JavaScript flattener, available under the BSD License.

Benjamin Atkin
  • 14,071
  • 7
  • 61
  • 60
0

In my case we have solved it by passing additional object to the action url.

public ActionResult Method(Customer customer, [Bind(Prefix="Budget")]Budget budget)

to make this happen you have to flatten the json data (before you sent it to controller) in following way:

How to pass complex type using json to ASP.NET MVC controller

Community
  • 1
  • 1
maciejgren
  • 119
  • 1
  • 4