Search code examples
asp.net.netajaxmodel-view-controller

Passing Parameter from AJAX call to .NET Controller as List<>


I am trying to pass an object from my ajax call to my controller. The controller has a List<> parameter. When I run the code the parameter comes in null or empty. The data is there when it is being passed into the ajax call.

My controller code:

[HttpPost]
public bool GeneratePassword([FromBody] List<AccountUser> users)
{
    bool success = false;

    success = users != null && users.Count > 0;

    if (success)
    {
        var userEdipis = users.Select(x => x.CAC_EDIPI).ToArray();

        foreach (int edipi in userEdipis)
        {
            List<AccountUser> allUserAccounts = users.FindAll(p => p.CAC_EDIPI ==edipi);
            CreateLetter(allUserAccounts, edipi);
        }
        return true;
    } else
    {
        return false;
    }           
}

My ajax call:

function generatePDF() {

    var users = [];
    var table = new DataTable('#dashboardTbl');
    table.rows({
        selected: true
    }).every(function(rowIdx, tableLoop, rowLoop) {
        var data = this.data();
        users.push({
            UserId: Number(data[6]),
            Username: data[2],
            LinkedAccountId: data[7],
            AccountName: data[3],
            CAC_EDIPI: data[8]
        });
    });

    var jsonData = JSON.stringify({
        users: users
    });

    $.ajax({
        type: "POST",
        url: '/APM/File/GeneratePassword',
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(jqXHR, textStatus, errorThrown) {
            $('#loading-overlay').fadeOut();
            alert("Unable to generate passwords and documents. " + errorThrown);
        }
    }).done(function(data) {
        alert("Password has been generated and documents have been emailed to account users.")
    });
}

Solution

  • Assume your AccountUser class has the schema equal to the object you push() in your javascript.

    As @dbc mentioned in comment, either change your JSON.stringify() code like:

    var jsonData = JSON.stringify(users);
    

    Or change your backend C# code into:

    class UserList 
    {
        List<AccountUser> Users {get; set;}
    }
    [HttpPost]
    public bool GeneratePassword([FromBody] UserList users)
    ...