Art F
Art F

Reputation: 4202

Accepting JSON in ASP.NET MVC 4

I have a JSON being send to a controller function of ASP.NET, the JSON looks something like this:

[{"Key":"Test23.txt","Size":6,"LastModified":"Thu, 01 Nov 2012 19:35:43 GMT"},
{"Key":"Test25.txt","Size":6,"LastModified":"Wed, 31 Oct 2012 21:02:51 GMT"},
{"Key":"Test28.txt","Size":6,"LastModified":"Thu, 01 Nov 2012 19:35:42 GMT"}]

How would I accept it in an MVC controller method and how do I parse it?

Thank you.

Upvotes: 3

Views: 1711

Answers (3)

Jarrett Meyer
Jarrett Meyer

Reputation: 19583

The default model binder can do all of this for you. There's no need to use any third party libraries. When passing collections into actions, they do need to be indexable. So you have to use an array or List.

// First, define your input model.
public class MyModel
{
  public string Key { get; set; }
  public int Size { get; set; }
  public string LastModified { get; set; }
}

// NExt, use that model in your action.
public ActionResult MyAction(MyModel[] things)
{
}

And everything should wire up for you.

Upvotes: 1

Stefan P.
Stefan P.

Reputation: 9519

public class Item
{
  public string Key {get;set;}
  public int Size {get;set;}
  public DateTime LastModified {get;set;}
}

public ActionResult MyAction(List<Item> items)
{

}

Upvotes: 0

dove
dove

Reputation: 20674

Mvc will automatically bind this to a viewModel if it matches.

public ActionResult SaveFiles(List<FileViewModel> filesViewModel){

}

where your FileViewModel would be something like this

public class FileViewModel
{
  public string Key {get;set}
  public int Size {get;set}
  public DateTime LastModified {get;set;}
}

Upvotes: 2

Related Questions