使用 jQuery Ajax 将对象列表传递到 MVC 控制器方法中 [英] Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

查看:27
本文介绍了使用 jQuery Ajax 将对象列表传递到 MVC 控制器方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法将对象数组传递到 MVC 控制器方法中jQuery 的 ajax() 函数.当我进入 PassThing() C# 控制器方法时,参数事物"为空.我已经尝试过使用一种 List for论点,但这也不起作用.我做错了什么?

I'm trying to pass an array of objects into an MVC controller method using jQuery's ajax() function. When I get into the PassThing() C# controller method, the argument "things" is null. I've tried this using a type of List for the argument, but that doesn't work either. What am I doing wrong?

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

推荐答案

根据 NickW 的建议,我能够使用 things = JSON.stringify({ 'things': things }); 这是完整的代码.

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(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 设置是绝对必要的.如果它们丢失,它将无法工作.经过多次反复试验,我发现了这一点.

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

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

To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

我希望这对其他人有帮助!

I hope this helps someone else!

这篇关于使用 jQuery Ajax 将对象列表传递到 MVC 控制器方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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