user290043
user290043

Reputation:

MVC3 Controller issue getting JSON from HTTP POST

I have a complicated json structure. Here it is simplified because it happens with this too:

{
"Id":0,
"Name":"Region Challenge",
"ModifiedOn":"2011-09-08T17:49:22",
"State":"Published",
"Goals":[
        {"Id":1,"Description":"some text here","DisplayOrder":1},
        {"Id":2,"Description":"some text here","DisplayOrder":2}
    ]
}

So, when this data is POST'd to controller, I have no problem getting this values for Id, Name, etc. However, Goals is null when I look at the locals window.

The signature is:

public JsonResult Save(int Id, String Name, DateTime ModifiedOn, String State, String Goals)

The POST Headers are:

User-Agent: Fiddler
Host: localhost:2515
Content-Type: application/json
Content-Length: 7336

How do I read in the data so that I can iterate over it?

Thanks! Eric

Upvotes: 1

Views: 611

Answers (2)

John x
John x

Reputation: 4031

define a class like

public class MyClass{
 public int Id{get;set;}
 public string Name {get;set;}
 public string State {get;set;}
 public IList<Goals> Goals {get;set;}
}

your Goal class will look like

Public class Goals{

 public int Id{get;set;}
 public string Description {get;set;}
 public int DisplayOrder {get;set}
}

after that just recieved it like

public JsonResult Save(MyClass _MyClass)

you will have to include the param name like if you are sending it via ajax

 data:{_MyClass: yourJSON}

Upvotes: 0

dknaack
dknaack

Reputation: 60496

Your Goals is a array or list. The simplest way is to

  1. Create a viewModel
  2. Change the ActionMethod

Sample

ViewModel

public class SomeThing
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime ModifiedOn { get; set; }
    public string State { get; set; }
    public List<Goal> Goals { get; set; }
}

public class Goal
{
    public int Id { get; set; }
    public string Description{ get; set; }
    public int DisplayOrder{ get; set; }
}

Changed ActionMethod

public JsonResult Save(SomeThing model)
{
   // model.Name ....
   // model.Id ...
   // model.Goals is your list of Goals

   // return Json
}

More Information

Upvotes: 1

Related Questions