小编典典

使用jQuery Ajax将对象列表传递到MVC控制器方法中

c#

我正在尝试使用jQuery的ajax()函数将对象数组传递到MVC控制器方法中。当我进入PassThing()C#控制器方法时,参数“
things”为空。我已经尝试使用List类型的参数进行此操作,但这也不起作用。我究竟做错了什么?

<script type="text/javascript">
    $(document).ready(function () {
        var things = [
            { id: 1, color: 'yellow' },
            { id: 2, color: 'blue' },
            { id: 3, color: 'red' }
        ];

        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Xhr/ThingController/PassThing',
            data: JSON.stringify(things)
        });
    });
</script>

public class ThingController : Controller
{
    public void PassThing(Thing[] things)
    {
        // do stuff with things here...
    }

    public class Thing
    {
        public int id { get; set; }
        public string color { get; set; }
    }
}

阅读 485

收藏
2020-05-19

共1个答案

小编典典

根据NickW的建议,我可以使用things = JSON.stringify({ 'things': things });下面的完整代码来使其工作。

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

我从中学到了两件事:

  1. 在ajax()函数中,绝对需要contentType和dataType设置。如果他们失踪了,那是行不通的。经过反复试验,我发现了这一点。

  2. 要将对象数组传递给MVC控制器方法,只需使用JSON.stringify({‘things’:Things})格式。

I hope this helps someone else!

2020-05-19