Passing data in ajax post

Scenario:

You must pass an object containing a list of auxiliary objects to the controller.

Problem:

I can get the value of the object, but not the value of the list of auxiliary objects inside the object.

The code:

index.cshtml

function sendData() { var student = { Id: 1, Name: "xxx", Marks: [{ Subject: "Maths", Mark:80 }, { Subject: "Science", Mark: 75 }] } $.ajax({ url: '@Url.Action("Receive", "Home")', data: student, success: function (data) { alert("done"); }, error: function (error) { alert('error For details refer console log'); console.log(error); } }); } 

HomeController.cs

 public ActionResult Receive(Student student) { ViewBag.Message = "Your contact page."; return View(); } 

Student.cs

 public class Student { public int Id { get; set; } public string Name { get; set; } public List<Marks> Marks { get; set; } } public class Marks { public string Subject { get; set; } public decimal Mark { get; set; } } 

Screenshot:

The Chrome debugger shows all the data that has been installed.

enter image description here

but in the controller I don't get the Marks value

enter image description here

Any help would be greatly appreciated. Thanks.

+6
source share
1 answer

You need to strengthen the data and set the ajax contentType and type parameters (note that it must be POST, otherwise you need to generate your data in a different way using fully qualified property names with dot notation - for example { Id: 1, .... , 'Marks[0].Subject': 'Maths', 'Marks[0].Mark': 80, ... } , in which case its existing ajax code will work without changes)

 var student = { .... }; $.ajax({ url: '@Url.Action("Receive", "Home")', data: JSON.stringify({ student: student }, // stringify type: 'POST', // add contentType: "application/json; charset=utf-8", //add success: function (data) { alert("done"); }, .... }); 

Note that the method returns an object, but you are not doing anything with this view. If you intend to update the DOM with this view, then the method should be return PartialView( ... ); and in the ajax success callback,

 success: function (data) { $(someElement).html(data); }, 
+5
source

Source: https://habr.com/ru/post/1015239/


All Articles