Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

前端 未结 13 1576
逝去的感伤
逝去的感伤 2020-11-22 14:22

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 \"t

相关标签:
13条回答
  • 2020-11-22 14:42

    Wrapping your list of objects with another object containing a property that matches the name of the parameter which is expected by the MVC controller works. The important bit being the wrapper around the object list.

    $(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; }
    }
    
    0 讨论(0)
  • 2020-11-22 14:43

    Formatting your data that may be the problem. Try either of these:

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

    Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)

    var postData = { things: things };
    ...
    data = postData
    
    0 讨论(0)
  • 2020-11-22 14:43

    This is working code for your query,you can use it.

    Controler

        [HttpPost]
        public ActionResult save(List<ListName> listObject)
        {
        //operation return
        Json(new { istObject }, JsonRequestBehavior.AllowGet); }
        }
    

    javascript

      $("#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");
       }
       });
    
    0 讨论(0)
  • 2020-11-22 14:44

    Modification from @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
          }
    
    0 讨论(0)
  • 2020-11-22 14:45

    I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:

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

    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
      }
    
    0 讨论(0)
  • 2020-11-22 14:45

    What I did when trying to send some data from several selected rows in DataTable to MVC action:

    HTML At the beginning of a page:

    @Html.AntiForgeryToken()
    

    (just a row is shown, bind from model):

     @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 which starts the JavaScript function:

     <button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
    

    JavaScript function:

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

    MVC action:

    [HttpPost]
    [ValidateAntiForgeryToken] //<--- This is important
    public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
    

    And MODEL in C#:

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

    CONCLUSION:

    The reason for ERROR:

    "Failed to load resource: the server responded with a status of 400 (Bad Request)"
    

    Is attribute: [ValidateAntiForgeryToken] for the MVC action StartWorkflow

    Solution in Ajax call:

      beforeSend: function (xhr) {//<--- This is important
                          xhr.setRequestHeader("RequestVerificationToken",
                          $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
    

    To send List of objects you need to form data like in example (populating list object) and:

    data: { model: list },

    type: "post",

    0 讨论(0)
提交回复
热议问题