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
ASP.NET MVC has the concept of ModelBinding. This means that if you add parameters to an Action method, MVC will try to fill these with the data you send.
This means you can change your code to:
// 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);
}
}
You can then use the following jquery to post your data:
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);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.