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

C# 使用jQuery Ajax将对象列表传递到MVC控制器方法,c#,asp.net-mvc,jquery,C#,Asp.net Mvc,Jquery,我正在尝试使用 jQuery的ajax()函数。当我进入PassThing()C#controller方法时, 参数“things”为空。我已经尝试过使用一种类型的列表 这是一个论点,但这也不起作用。我做错了什么 <script type="text/javascript"> $(document).ready(function () { var things = [ { id: 1, color: 'yellow' },

我正在尝试使用 jQuery的ajax()函数。当我进入PassThing()C#controller方法时, 参数“things”为空。我已经尝试过使用一种类型的列表 这是一个论点,但这也不起作用。我做错了什么

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

$(文档).ready(函数(){
变量事物=[
{id:1,颜色:'yellow'},
{id:2,颜色:'blue'},
{id:3,颜色:'red'}
];
$.ajax({
contentType:'application/json;charset=utf-8',
数据类型:“json”,
键入:“POST”,
url:“/Xhr/ThingController/PassThing”,
数据:JSON.stringify(things)
});
});
公共类ThingController:控制器
{
公共无效通行证(Thing[]things)
{
//在这里做事。。。
}
公共类事物
{
公共int id{get;set;}
公共字符串颜色{get;set;}
}
}

格式化可能是问题所在的数据。请尝试以下任一方法:

data: '{ "things":' + JSON.stringify(things) + '}',
或(来自)


使用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; }
}
$(文档).ready(函数(){
变量事物=[
{id:1,颜色:'yellow'},
{id:2,颜色:'blue'},
{id:3,颜色:'red'}
];      
things=JSON.stringify({'things':things});
$.ajax({
contentType:'application/json;charset=utf-8',
数据类型:“json”,
键入:“POST”,
url:“/Home/PassThings”,
数据:事物,
成功:函数(){
$('#result').html(''PassThings()'已成功调用');
},
失败:函数(响应){
$('#result').html(响应);
}
}); 
});
公共物品(列出物品)
{
var t=事物;
}
公共类事物
{
公共int Id{get;set;}
公共字符串颜色{get;set;}
}
我从中学到了两件事:

  • contentType和dataType设置在ajax()函数中是绝对必要的。如果他们不见了就没用了。经过反复试验,我发现了这一点

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


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

    你就不能这么做吗

    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...
    }
    
    [HttpPost]
    公共物品(IEnumerable物品)
    {
    //在这里做事。。。
    }
    
    对于这一切,我有一个完美的答案:我尝试了太多的解决方案,但最终无法让自己管理,请在下面找到详细答案:

           $.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);
                }
            });
    
    控制器

    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
      }
    
    公共类的东西
    {
    公共int id{get;set;}
    公共字符串颜色{get;set;}
    }
    公共JsonResult方法测试(IEnumerable datav)
    {
    //现在datav拥有了你所有的价值观
    }
    
    如果您使用的是ASP.NET Web API,那么您应该只传递
    数据:JSON.stringify(things)

    您的控制器应该如下所示:

    public class PassThingsController : ApiController
    {
        public HttpResponseMessage Post(List<Thing> things)
        {
            // code
        }
    }
    
    公共类密码控制器:ApiController
    {
    公共httpresponsemessagepost(列出内容)
    {
    //代码
    }
    }
    
    这是用于查询的工作代码,您可以使用它。

    控制器


    修改自@veeresh i

     var data=[
    
                            { id: 1, color: 'yellow' },
                            { id: 2, color: 'blue' },
                            { id: 3, color: 'red' }
                            ]; //parameter
            var para={};
            para.datav=data;   //datav from View
    
    
            $.ajax({
                        traditional: true,
                        url: "/Conroller/MethodTest",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        data:para,
                        success: function (data) {
                            $scope.DisplayError(data.requestStatus);
                        }
                    });
    
    In MVC
    
    
    
    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
          }
    
    var数据=[
    {id:1,颜色:'yellow'},
    {id:2,颜色:'blue'},
    {id:3,颜色:'red'}
    ]; //参数
    var para={};
    第datav段=数据//来自视图的数据
    $.ajax({
    传统的:是的,
    url:“/Conroller/MethodTest”,
    类型:“POST”,
    contentType:“应用程序/json;字符集=utf-8”,
    数据:第,
    成功:功能(数据){
    $scope.DisplayError(data.requestStatus);
    }
    });
    在MVC中
    公共类事物
    {
    公共int id{get;set;}
    公共字符串颜色{get;set;}
    }
    公共JsonResult方法测试(IEnumerable datav)
    {
    //现在datav拥有了你所有的价值观
    }
    
    我实现这一点的唯一方法是将JSON作为字符串传递,然后使用
    JavaScriptSerializer.Deserialize(字符串输入)
    对其进行反序列化,如果这是MVC4的默认反序列化程序,这是非常奇怪的

    我的模型有嵌套的对象列表,使用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);
    
    $.ajax({
    键入:“POST”,
    url:“/Agri/Map/SaveSelfValuation”,
    数据:{json:json.stringify(model)},
    数据类型:“文本”,
    成功:功能(数据){
    [HttpPost]
    公共JsonResult DoSomething(字符串json)
    {
    var model=new JavaScriptSerializer()。反序列化(json);
    
    使用另一个对象包装对象列表,该对象包含与MVC控制器期望的参数名称匹配的属性。 重要的一点是对象列表的包装器

    $(document).ready(function () {
        var employeeList = [
            { id: 1, name: 'Bob' },
            { id: 2, name: 'John' },
            { id: 3, name: 'Tom' }
        ];      
    
        var Employees = {
          EmployeeList: employeeList
        }
    
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: '/Employees/Process',
            data: Employees,
            success: function () {          
                $('#InfoPanel').html('It worked!');
            },
            failure: function (response) {          
                $('#InfoPanel').html(response);
            }
        }); 
    });
    
    
    public void Process(List<Employee> EmployeeList)
    {
        var emps = EmployeeList;
    }
    
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    $(文档).ready(函数(){
    var employeeList=[
    {id:1,名称:'Bob'},
    {id:2,名字:'John'},
    {id:3,名字:'Tom'}
    ];      
    var雇员={
    雇员名单:雇员名单
    }
    $.ajax({
    数据类型:“json”,
    键入:“POST”,
    url:“/Employees/Process”,
    数据:员工,
    成功:函数(){
    $('InfoPanel').html('It worked!');
    },
    失败:函数(响应){
    $('#InfoPanel').html(res
    
      $("#btnSubmit").click(function () {
        var myColumnDefs = [];
        $('input[type=checkbox]').each(function () {
            if (this.checked) {
                myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
            } else {
                myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
            }
        });
       var data1 = { 'listObject': myColumnDefs};
       var data = JSON.stringify(data1)
       $.ajax({
       type: 'post',
       url: '/Controller/action',
       data:data ,
       contentType: 'application/json; charset=utf-8',
       success: function (response) {
        //do your actions
       },
       error: function (response) {
        alert("error occured");
       }
       });
    
     var data=[
    
                            { id: 1, color: 'yellow' },
                            { id: 2, color: 'blue' },
                            { id: 3, color: 'red' }
                            ]; //parameter
            var para={};
            para.datav=data;   //datav from View
    
    
            $.ajax({
                        traditional: true,
                        url: "/Conroller/MethodTest",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        data:para,
                        success: function (data) {
                            $scope.DisplayError(data.requestStatus);
                        }
                    });
    
    In MVC
    
    
    
    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
          }
    
        $.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);
    
    $(document).ready(function () {
        var employeeList = [
            { id: 1, name: 'Bob' },
            { id: 2, name: 'John' },
            { id: 3, name: 'Tom' }
        ];      
    
        var Employees = {
          EmployeeList: employeeList
        }
    
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: '/Employees/Process',
            data: Employees,
            success: function () {          
                $('#InfoPanel').html('It worked!');
            },
            failure: function (response) {          
                $('#InfoPanel').html(response);
            }
        }); 
    });
    
    
    public void Process(List<Employee> EmployeeList)
    {
        var emps = EmployeeList;
    }
    
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: mycontrolleraction,
            data: JSON.stringify(things)
        });
    
        [HttpPost]
        public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
        {
            return Ok();
        }
    
    @Html.AntiForgeryToken()
    
     @foreach (var item in Model.ListOrderLines)
                    {
                        <tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
                            <td>@item.OrderId</td>
                            <td>@item.OrderDate</td>
                            <td>@item.RequestedDeliveryDate</td>
                            <td>@item.ProductName</td>
                            <td>@item.Ident</td>
                            <td>@item.CompanyName</td>
                            <td>@item.DepartmentName</td>
                            <td>@item.ProdAlias</td>
                            <td>@item.ProducerName</td>
                            <td>@item.ProductionInfo</td>
                        </tr>
                    }
    
     <button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
    
      function ProcessMultipleRows() {
                if ($(".dataTables_scrollBody>tr.selected").length > 0) {
                    var list = [];
                    $(".dataTables_scrollBody>tr.selected").each(function (e) {
                        var element = $(this);
                        var orderid = element.data("orderid");
                        var iscustom = element.data("iscustom");
                        var orderlineid = element.data("orderlineid");
                        var folderPath = "";
                        var fileName = "";
    
                        list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
                    });
    
                    $.ajax({
                        url: '@Url.Action("StartWorkflow","OrderLines")',
                        type: "post", //<------------- this is important
                        data: { model: list }, //<------------- this is important
                        beforeSend: function (xhr) {//<--- This is important
                          xhr.setRequestHeader("RequestVerificationToken",
                          $('input:hidden[name="__RequestVerificationToken"]').val());
                          showPreloader();
                        },
                        success: function (data) {
    
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
    
                        },
                         complete: function () {
                             hidePreloader();
                        }
                    });
                }
            }
    
    [HttpPost]
    [ValidateAntiForgeryToken] //<--- This is important
    public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
    
    public class WorkflowModel
     {
            public int OrderId { get; set; }
            public int OrderLineId { get; set; }
            public bool IsCustomOrderLine { get; set; }
            public string FolderPath { get; set; }
            public string FileName { get; set; }
     }
    
    "Failed to load resource: the server responded with a status of 400 (Bad Request)"
    
      beforeSend: function (xhr) {//<--- This is important
                          xhr.setRequestHeader("RequestVerificationToken",
                          $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
    
    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);
        }
    });