Json字符串列表是空的

时间:2012-04-20 07:40:00

标签: asp.net-mvc json http-post

我将一个json字符串集合从Android设备传递给.net MVC HttpPost方法。我的json字符串就像。

{"collection",[{"Name":"A","Age":"12","Class":"10"},{"Name":"B","Age":"12","Class":"10"}]}

我的MVC控制功能是:

  [HttpPost]
    public ActionResult Create(string[] collection)
    {
        try
        {
            // TODO: Add insert logic here
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            List<Model.StudentBehaviour> stdbehaviour_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.StudentBehaviour>>(collection);
            Lib.StudentModule.StudentManager.InsertStudentBehaviours(stdbehaviour_list);               
            return Json("success", JsonRequestBehavior.AllowGet);
        }
        catch
        {
            return Json("exception", JsonRequestBehavior.AllowGet);
        }
    }

函数参数值为

collection = "(Collection)"

集合中的期望值是

collection[0] 
Name = A 
Age = 12
Class = 10
collection[1] 
Name = B 
Age = 12
Class = 10

请帮助解决此问题

提前致谢

1 个答案:

答案 0 :(得分:0)

ASP.NET MVC具有ModelBinding的概念。这意味着如果向Action方法添加参数,MVC将尝试使用您发送的数据填充这些参数。

这意味着您可以将代码更改为:

 // Example of your Student class. 
 // Make sure that all properties you want to bind to are public
 public class Student
 {
     public string Name { get; set; }
     public int Age { get; set; }
     public int Class { get; set; }
 }

// Example of an Action method. Note that instead of taking a string as parameter,
// you just accept a collection of Student objects.
[HttpPost]
public JsonResult Create(List<Student> collection)
{
    if (ModelState.IsValid)
    {
        return Json("success", JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json("exception", JsonRequestBehavior.AllowGet);
    }
}

然后,您可以使用以下jquery发布您的数据:

function sendData() {    
        var data = [{ 'Name': 'A', 'Age': '12', 'Class': '10' },
            { 'Name': 'B', 'Age': '12', 'Class': '10' }];

        var collection = JSON.stringify(data);

        $.ajax({
            url: "Home/Create",
            type: "POST",
            data: collection,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
        }).done(function (msg) {
            alert("Data Saved: " + msg);
        });
    }