0

am passing a json string collection from Android device to .net MVC HttpPost method. my json string is like.

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

My MVC control function is:

  [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);
        }
    }

the function parameter value is

collection = "(Collection)"

expected value in collection is

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

please help to fix this issue

Thanks in advance

4

1 回答 1

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);
        });
    }
于 2012-04-20T08:11:59.637 回答