3

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.

3
  • You may use Json.net for parsing. Commented Nov 2, 2012 at 15:55
  • Do you control the process of generating this JSON and making server request? Commented Nov 2, 2012 at 15:59
  • I have some control, I am developing the front-end which uses ExtJs, which in turn generates the JSON. Commented Nov 2, 2012 at 16:26

3 Answers 3

2

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;}
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Nope, I use empty MVC4 project and there is no "default model binder".
0
public class Item
{
  public string Key {get;set;}
  public int Size {get;set;}
  public DateTime LastModified {get;set;}
}

public ActionResult MyAction(List<Item> items)
{

}

Comments

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.