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

前端 未结 13 1736
逝去的感伤
逝去的感伤 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 EmployeeList)
    {
        var emps = EmployeeList;
    }
    
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

提交回复
热议问题