在ajax post问题中传递数据 [英] Passing data in ajax post issue

查看:167
本文介绍了在ajax post问题中传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

需要将包含子对象列表的对象传递给控制器​​。

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

问题:

我能够获得对象的值但不能对象内的子对象列表的值。

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

代码:

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

屏幕截图:

Chrome调试器显示已设置的所有数据。

Chrome debugger shows all the data were set.

但在控制器中我没有得到马克斯的价值

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

任何帮助将不胜感激。谢谢。

Any help would be appreciated. Thank you.

推荐答案

您需要对数据进行字符串化,并设置 contentType 键入 ajax选项(请注意,它必须是POST,否则您需要使用带有点表示法的完全限定属性名称以不同方式生成数据 - for示例 {Id:1,....,'Marks [0] .Subject':'Maths','Marks [0] .Mark':80,...} ,在这种情况下,你现有的ajax代码无需修改即可工作)

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");
    },
    ....
});

请注意,您的方法返回一个视图,但您没有对该视图执行任何操作。如果您打算使用该视图更新DOM,则该方法应为返回PartialView(...); 并在ajax成功回调中,

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

这篇关于在ajax post问题中传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆