简体   繁体   中英

Posting array to mvc controller via ajax with knockoutjs

I'm having issues POSTing an array to my controller. I am sending a list of items and in the items there's an array of groups. The array value shows as null in the controller even though the sendData variable I'm posting has the array.

Here's my data I'm POSting. In this case the variable data is "[{"id":"123456789","firstName":"John","lastName":"Doe","UserGroups":["1","2"]}]"

My model for the User:

 [Display(Name = "SSO")]
[Required]
        public virtual string ID { get; set; }

        [Display(Name = "First Name")]
        [Required]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        [Required]
        public string LastName { get; set; }

        [Display(Name = "User Group(s)")]
        public UserGroupModels[] UserGroup { get; set; }

Model for Groups. You'll notice the One-to-Many relationship

public class UserGroupModels
    {
        public int ID { get; set; }

        public string MAMUserGroup { get; set; }
    }

The AJAX call. You'll notice I'm using KnockoutJS as well

self.save = function (form) {


    sendData = ko.toJSON(self.users);//value is "[{"id":"123456789","firstName":"John","lastName":"Doe","UserGroups":["1","2"]}]"


    $.ajax({
        url: '/Users/CreateMultiple',
        contentType: 'application/json',
        async: true,
        traditional: true,
        type: 'POST',
        dataType: 'json',
        data: sendData,
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("FAIL: ");
            alert("ERROR: " + errorThrown)
            hidePleaseWait();
        },
        success: function (response) {
            hidePleaseWait();
            console.log(response.alreadyExistList);

Here's my controller

public async Task<ActionResult> CreateMultiple(List<User> users)
        {do something...}

When I look at the List<User> user 's locals I'm seeing the correct number of UserGroups in the array (2 in this case), but each value is null. For example users[0].UserGroups[0]=null , users[0].UserGroups[1]=null

UserGroups json数组中的项目应该是为UserGroupModels类建模的对象。

"UserGroups":[{"ID":"1"},{"ID":"2"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM