Kacey Ezerioha Kacey Ezerioha - 1 month ago 9
C# Question

How Do I Pass Array of Checked Items into Object in AngularJS?

I have an input checkbox enclosed in

ng-repeat
with a function
vm.addRemoveItem()
for
ng-change
that stores all checked items in an array
vm.itemsArr
. I want to be able to pass the array to a c# method via webAPI but the array isn't passed into the variable I use. Please see the proper description in code below

Checkbox in ng-repeat

<input type="checkbox" ng-model="item.selected" ng-change="vm.addRemoveItem()" value={{item.id}} /> {{item.title}}


function that stores all checked items in an array

vm.addRemoveItem = function () {
vm.itemsArr = [];
angular.forEach(vm.itemList, function (item) {
if (item.selected) {
vm.itemsArr.push(item.id);
}
})
}


I confirmed that the above function works as I was able to display the content of the array of checked items using
alert()
.

Passing the values to c# through webAPI (My challenge)

vm.itemObj= {
itemInfoId: $stateParams.id,
itemValues: JSON.stringify(vm.itemsArr)
};


The challenge here is when I pass the above object
itemObj
into the function that is called through webAPI, it returns validation error because
itemValues
is null but
itemInfoId
has the right value. How do I pass the content of the array into
itemValues
?

C# Function

public async Task AddSubjectToClassInfoAsync(AddItemsInput input)
{
//Code to add values to database
}

//AddItemsInput Class
public class AddSubjectsInput
{
public int ItemInfoId { get; set; }

public string[] ItemValues { get; set; }
}


Angular Function Call

vm.add = function () {
subjectService.addtoDBAsync(vm.itemObj).success(function () {
$modalInstance.close();
})
};

Answer

As you placed the creation of vm.itemObj directly inside of the controller, it is being created as soon as the controller is built, this means vm.itemsArr has not yet been initialised or populated, so you are getting a null reference.

Change the creation of object vm.itemObj to;

vm.itemObj= {
    itemInfoId: $stateParams.id,
    itemValues: []
};

Now you can either push items to vm.itemObj.itemValues directly, or when required replace itemValues with another array probably at the point you are about to perform the api call.

vm.itemObj.itemValues = vm.itemsArr;
Comments