Kacey Ezerioha Kacey Ezerioha - 2 months ago 18
C# Question

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

I have an input checkbox enclosed in

with a function
that stores all checked items in an array
. 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) {

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

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
into the function that is called through webAPI, it returns validation error because
is null but
has the right value. How do I pass the content of the array into

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 () {


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;