为了账号安全,请及时绑定邮箱和手机立即绑定

使用jQueryAjax将对象列表传递给MVC控制器方法

使用jQueryAjax将对象列表传递给MVC控制器方法

缥缈止盈 2019-07-25 12:14:25
使用jQueryAjax将对象列表传递给MVC控制器方法我试图使用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; }     }}
查看完整描述

2 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

使用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.strgify({‘Things’:Things})格式即可。

我希望这能帮到别人!




查看完整回答
反对 回复 2019-07-27
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

你就不能这么做吗?

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

.然后用

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



查看完整回答
反对 回复 2019-07-27
  • 2 回答
  • 0 关注
  • 287 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信