在ASP.NET MVC 4中接受JSON

3
我有一个JSON被发送到ASP.NET的控制器函数,JSON看起来像这样:
[{"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"}]

我该如何在MVC控制器方法中接受它,以及如何解析它?

谢谢。


你可以使用 Json.net 进行解析。 - Adil
你控制生成这个JSON文件和进行服务器请求的过程吗? - Robert Koritnik
我有一些控制权,我正在开发使用ExtJs的前端,它反过来生成JSON。 - Art F
3个回答

2

如果匹配,Mvc将自动将此绑定到ViewModel。

public ActionResult SaveFiles(List<FileViewModel> filesViewModel){

}

您的FileViewModel可能如下所示:
public class FileViewModel
{
  public string Key {get;set}
  public int Size {get;set}
  public DateTime LastModified {get;set;}
}

1
默认的模型绑定器可以为您完成所有这些操作,无需使用任何第三方库。在将集合传递到操作时,它们需要是可索引的。因此,您必须使用一个数组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)
{
}

一切都应该为您连接好。


不,我使用空的MVC4项目,没有“默认模型绑定器”。 - Jeson Martajaya
是的,有的... http://msdn.microsoft.com/zh-cn/library/system.web.mvc.defaultmodelbinder.aspx - Jarrett Meyer

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)
{

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接