ItsDanny
ItsDanny

Reputation: 165

Webapi parameter is null on Method

I'm trying to post back a list of data objects (WorkOrders), in JSON format to my Webapi controller, this works amazingly well, except for the slight flaw in that the data object parameter (savemodel) is null when it hits the webapi controller. This is a snip from the JS (slots is mock data)

var slots = [];    
            slots.push({ 'WorkOrder': 'XX21', 'OrderDate': '2015-10-11 00:00:00', 'Slot': '1', 'SageRef': 'HS11' });
            slots.push({ 'WorkOrder': 'XX22', 'OrderDate': '2015-10-12 00:00:00', 'Slot': '2', 'SageRef': 'HS12' })
            slots.push({ 'WorkOrder': 'XX23', 'OrderDate': '2015-10-13 00:00:00', 'Slot': '3', 'SageRef': 'HS13' });
            console.log(JSON.stringify({ 'savemodel': slots }))
            $.ajax({
                type: "POST",
                url: 'http://localhost:55821/api/schedule',
                data: JSON.stringify({ 'savemodel': slots }),
                contentType: 'application/json; charset=utf-8'                
            }).success(function (data) {
                $scope.$apply(function () {
                    if (data.SaveMessage.length > 0) {
                      // do something
                    }
                    else {
                      // do something else
                    }
                });
            });

The model:

    public class WorkOrderModel
{
    public string WorkOrder { get; set; }
    public string OrderDate { get; set; }
    public string SlotNumber { get; set; }
    public string SageRef { get; set; }
}

The postback method:

 [HttpPost]
        public IHttpActionResult UpdateWorkOrder([FromBody]List<WorkOrderModel> savemodel)
        {
            StringBuilder saveMessage = new StringBuilder();
            foreach (WorkOrderModel model in savemodel)
            {
                   // save the WO model object  here                
            }
            if (saveMessage.Length > 0)
            {
                return Ok(new { SaveMessage = "There were issues: " + saveMessage.ToString() });
            }
            else
            {
                return Ok(new { SaveMessage = "" });
            }
        }

Posted JSON Null parameter in the WebApi Controller This is driving me nuts so any help will be hugely appreciated at this stage!

Regards, itsdanny

Upvotes: 4

Views: 388

Answers (1)

ItsDanny
ItsDanny

Reputation: 165

Sorted, it changed

data: JSON.stringify({ 'savemodel': slots}),

to

data: JSON.stringify(slots),

Upvotes: 1

Related Questions