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

Hal*_*yon 107 c# asp.net-mvc jquery

我正在尝试使用jQuery的ajax()函数将一个对象数组传递给MVC控制器方法.当我进入PassThing()C#控制器方法时,参数"things"为null.我已经尝试使用一种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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hal*_*yon 172

使用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; }
}
Run Code Online (Sandbox Code Playgroud)

我从中学到了两件事:

  1. 在ajax()函数中绝对需要contentType和dataType设置.如果它们丢失,它将无法工作.经过多次试验和错误,我发现了这一点.

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

我希望这有助于其他人!

  • 需要注意的两件事:JSON.stringify并指定'contentType'. (9认同)
  • 我遇到了同样的问题,并添加了contentType修复它.谢谢! (7认同)
  • 无论出于何种原因,我不得不使用`data:JSON.stringify(things),` (2认同)
  • 对于aspnetcore 2,请记住在控制器函数中添加[FromBody],否则它将无法工作。 (2认同)

小智 30

你不能这样做吗?

var things = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
   function () {
        $('#result').html('"PassThings()" successfully called.');
   });
Run Code Online (Sandbox Code Playgroud)

......用你的标记你的行动

[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
    // do stuff with things here...
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是最好的答案.在这种情况下不应使用JSON.stringify (2认同)
  • 它对我有用。绝对是最好的答案。我不知道为什么 Halcyon 实现不起作用。PassThings 函数被调用,但“事物”输入变量是空的,即使它在调用之前在 javascript 中填充。 (2认同)

nic*_*k_w 12

格式化可能存在问题的数据.尝试以下任何一种:

data: '{ "things":' + JSON.stringify(things) + '}',
Run Code Online (Sandbox Code Playgroud)

或者(如何在没有表单的情况下将字符串数组发布到ASP.NET MVC控制器?)

var postData = { things: things };
...
data = postData
Run Code Online (Sandbox Code Playgroud)


Gon*_*ing 11

我正在使用.Net Core 2.1 Web应用程序,但无法在此处获得单一答案.我要么得到一个空白参数(如果方法被调用)或500服务器错误.我开始玩各种可能的答案组合,最后得到了一个有效的结果.

就我而言,解决方案如下:

脚本 - 对原始数组进行字符串化(不使用命名属性)

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: mycontrolleraction,
        data: JSON.stringify(things)
    });
Run Code Online (Sandbox Code Playgroud)

在控制器方法中,使用[FromBody]

    [HttpPost]
    public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
    {
        return Ok();
    }
Run Code Online (Sandbox Code Playgroud)

失败包括:

  • 命名内容

    data:{content:nodes},//服务器错误500

  • 没有contentType = Server错误500

笔记

  • dataType不需要,尽管有些答案说,因为它用于响应解码(因此这里与请求示例无关).
  • List<Thing> 也适用于控制器方法


Vee*_*asi 8

我对这一切都有完美的答案:我尝试了很多无法最终自己管理的解决方案,请在下面找到详细解答:

       $.ajax({
            traditional: true,
            url: "/Conroller/MethodTest",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify( 
               [
                { id: 1, color: 'yellow' },
                { id: 2, color: 'blue' },
                { id: 3, color: 'red' }
                ]),
            success: function (data) {
                $scope.DisplayError(data.requestStatus);
            }
        });
Run Code Online (Sandbox Code Playgroud)

的Controler

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

public JsonResult MethodTest(IEnumerable<Thing> datav)
    {
   //now  datav is having all your values
  }
Run Code Online (Sandbox Code Playgroud)


mor*_*est 7

我能让它工作的唯一方法是将JSON作为字符串传递,然后使用反序列化JavaScriptSerializer.Deserialize<T>(string input),如果这是MVC 4的默认反序列化器,这很奇怪.

我的模型有嵌套的对象列表,我使用JSON数据得到的最好的是最上面的列表,其中包含正确的项目数,但项目中的所有字段都为空.

这种事情不应该那么难.

    $.ajax({
        type: 'POST',
        url: '/Agri/Map/SaveSelfValuation',
        data: { json: JSON.stringify(model) },
        dataType: 'text',
        success: function (data) {

    [HttpPost]
    public JsonResult DoSomething(string json)
    {
        var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
Run Code Online (Sandbox Code Playgroud)


小智 5

这对我来说效果很好:

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: '/Controller/action',
    data: { "things": things },
    success: function () {
        $('#result').html('"PassThings()" successfully called.');
    },
    error: function (response) {
        $('#result').html(response);
    }
});
Run Code Online (Sandbox Code Playgroud)

“ContentType”大写“C”。