Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - Passing data in ajax post issue

Scenario :

Need to pass an object which contains a list of sub objects to the controller.

Issue :

I'm able to get the object's value but not the value of list of sub objects inside the object.

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:

Chrome debugger shows all the data were set.

enter image description here

but in controller i'm not getting the value of Marks

enter image description here

Any help would be appreciated. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to stringify the data, and set the contentType and type ajax options (note that it needs to be a 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 your existing ajax code will work without modification)

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 you method is returning a view, but you not doing anything with that view. If your intention is to update the DOM with that view, then the method should be return PartialView( ... ); and in the ajax success callback,

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...