Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting complex JSON to MVC controller. How do I name nested objects?

I have a controller set up that's expecting this object to be posted to it:

public class PrintJob
{
    public string BarTenderFile { get; set; }
    public string PrinterName { get; set; }
    public List<TagLabel> Queue { get; set; } 
}

public class TagLabel
{
    public string Season { get; set; }
    public string STSStyle { get; set; }
    public string VStyle { get; set; }
    public string ColorCode { get; set; }
    public int CODI { get; set; }
    public string SizeDesc { get; set; }
    public string StyleDesc { get; set; }
    public string ColorDesc { get; set; }
    public string Vendor { get; set; }
    public int Qty { get; set; }
    public long UPC { get; set; }
    public double CurrRetail { get; set; }
    public double OrigRetail { get; set; }
    public string AvailableIn { get; set; }
}

I'm trying to submit to my controller via AJAX using JSON to represent my object. It works fine for the top level attributes of PrintJob, the controller sees the values for both the BarTenderFile and PrinterName attributes. The problem is the Queue. My javascript looks like this:

var queue = [];

$('#queue tr').each(function () {
    var tagLabel = $.parseJSON($(this).find('pre').text());
    queue.push(tagLabel);
});

var data = {
    "BarTenderFile": $('#btFile').val(),
    "PrinterName": $('#printer').val(),
    "Queue": queue
}

$.ajax({
    type: 'POST',
    url: window.submitQueueUrl,
    dataType: "application/json",
    data: data,
    success: function (returnVal) {
        // Do success stuff
    }
});

The JSON for each Queue object is stored within hidden <pre> tags on the page, formatted so that each name matches the names in my TagLabel object. I figured this would be easier than using scads of hidden input fields. The JSON being sent generates no errors and the back end code digests it without issue. The problem is when I submit this to the controller the Queue is populated by a list of object. The end result is, in my controller, the Queue will have however many queue items I selected but each queue item is populated by nulls and zeroes. How do I tell my controller to recognize each queue item is a TagLabel instead of a generic object?

like image 549
Dan S. Avatar asked Feb 14 '23 04:02

Dan S.


1 Answers

Expanding on my comment: the data isn't being encoded into JSON. jQuery will try to build normal URL encoded data from the objects (this explains why the first part is received).

Change to encode the JSON:

$.ajax({
    data: JSON.stringify(data),
    contentType : 'application/json' // also set the content type
    ...
});
like image 75
MrCode Avatar answered Feb 16 '23 03:02

MrCode