CrazyLegs
CrazyLegs

Reputation: 608

How do I send a JavaScript array to a controller in a .net core 3.1 application?

The javascript side of things looks like this:

var self = this;
    self.services = ko.observableArray([]);

    self.saveServices = function () {
        if (self.services().length > 0) {
            
            var obj = JSON.stringify({ services: self.services() });

            $.ajax({
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                type: "POST",
                url: '/Business/SaveServices',
                data: obj,
                success: function (data) {
                    $("#saveModal").modal('show');
                    if (!data) {
                        $("#saveDetails").text('Processing error, please try again or email us.');
                        return;
                    } else if (data === "saved") {
                        $("#saveDetails").text('Saved changes.');
                        setTimeout(function () {
                            $('#saveModal').modal('hide');
                        }, 2500);
                    } else {
                        $("#saveDetails").text(data);
                    }
                },
                error: function (error) {
                    $("#saveModal").modal('show');
                    $("#saveDetails").text('Processing error, please try again or email us.');
                }
            });
        }
    }

Then my controller looks like this:

[HttpPost]
    public async Task<JsonResult> SaveServices([FromBody]SaveServicesRequest saveServicesRequest)
    {
        try
        {
            if (User.Identity.IsAuthenticated)
            {
                return Json("saved");
            }
            return Json("User is not authenticated.");
        }
        catch (Exception ex)
        {
            logger.Error(ex + ". Users Email address: " + User.Identity.Name);
            return Json("Processing error, please try again or email us.");
        }
    }
    public class SaveServicesRequest
    {
        public List<services> services { get; } = new List<services>();
    }
    public class services
    {
        public string service { get; set; }
    }

Am hitting the controller but the array of items I'm expecting is not returned (saveServicesRequest is empty), I cannot seem to pass an array in any form. Anyone see what am doing wrong? The data/json is being sent client side, think the problem might lie in how am building the json and receiving it.

Upvotes: 1

Views: 669

Answers (1)

haldo
haldo

Reputation: 16701

The problem is that you're initializing services to a new list in SaveServicesRequest. The properties should also have public getters and setters for model binding.

Try updating your class to:

public class SaveServicesRequest
{
    public List<services> services { get; set; }
}

Upvotes: 1

Related Questions