1

The instant the post to the controller happens, the screen show the 415 error...so I am thinking that even though the data goes through somehow my json structure must not be correct.

View Ajax:

function SubAll() {
var selectedValues = 
$('#timesheet').DataTable().column(0).checkboxes.selected().toArray();

var instructions = []; //create array of objects
for (var i = 0; i < selectedValues.length; i++) {
instructions.push({ TimeId: selectedValues[i] });
}

var jsonObject = { MasterIds: instructions };

$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(jsonObject),
success: function (result) {
console.log(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = 
"/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};

Controller:

public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)

Class Objects:

public class ValueContainer
{
    public List<Value> MasterIds { get; set; }
}

public class Value
{
    public Guid TimeId { get; set; }
}

Payload:

{"MasterIds":[{"TimeId":"ad98749f-9083-464b-aac2-0d685a7de809"}]}

UPDATE #1

As it turns out the fix is the way I was calling the function. Instead of the button onclick="SubAll()" I replaced that with a simple and used jQuery to intercept the click event, prevent it, and then call into the function...and now no 415 error.

View Button

<button id="ApproveAll" class="btn btn-success">Approve All</button>

View jQuery

 $(document).ready(function () {
        timesheet = $('#timesheet').DataTable({
            responsive: {
                details: {
                    renderer: function (api, rowIdx, columns) {
                        var data = $.map(columns, function (col, i) {
                            return col.hidden ?
                                '<tr data-dt-row="' + col.rowIndex + '" 
data-dt-column="' + col.columnIndex + '">' +
                                '<td>' + col.title + ':' + '</td> ' +
                                '<td>' + col.data + '</td>' +
                                '</tr>' :
                                '';
                        }).join('');

                        return data ?
                            $('<table/>').append(data) :
                            false;
                    }
                }
            },
            columnDefs: [
            {
                targets: 0,
                orderable: false,
                searchable: false,
                checkboxes: true
            },
            {
                targets: 5,
                visible: false
            },
            {
                targets: 6,
                visible: false
            }
            ],
            order: [
                [1, 'asc']
            ]
        });

        $('#ApproveAll').on('click',
            function (e) {
                var selectedValues = 
$('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
                var instructions = []; //create array of objects
                for (var i = 0; i < selectedValues.length; i++) {
                    instructions.push(selectedValues[i]);
                }

                var jsonObject = { MasterIds: instructions };

                $.ajax({
                    url: "/Admin/ApproveAllTimesheets",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    data: JSON.stringify(jsonObject),
                    traditional: true,
                    statusCode: {
                        415: function () {
                            Response.redirect("/Admin/Index");
                        }
                    },
                    success: function (result) {
                        console.log(result);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        if (xhr.status == 401) { alert("Session 
Expired!"); window.location = "/Account"; }
                        else {
                            alert('Content load failed!', "info");
                        }
                    }
                });
                e.preventDefault();
            });
    });
Michael
  • 15
  • 1
  • 6
  • I think you can see [this](https://stackoverflow.com/questions/22566433/http-415-unsupported-media-type-error-with-json). Can you share with us your controller ? – jibeeeee Feb 04 '19 at 18:46
  • #1) That link is for google-gson-2.2.4 library for json...I am using the Newtonsoft.json library. #2) My controller logic does not matter as the 415 happens immediately...I have a breakpoint on an empty string declaration as soon as the method is entered. – Michael Feb 04 '19 at 19:36
  • No, a 415 literally means the action does not accept the particular content type submitted (i.e. application/json). It doesn't even bother to try to parse it, so whether your JSON is syntactically correct or not is inconsequential at this point. Now, the odd thing is that JSON is supported out of the box, so did you do any customization to the input/output formatters in your Startup.cs? – Chris Pratt Feb 04 '19 at 19:46
  • I did not customize the formatters. I have the same suspicion about Content-Type...I changed the model to be Value[] instead of List...still got 415 and the data still went to the method. – Michael Feb 04 '19 at 20:13
  • https://imgur.com/KR3RHrQ – Michael Feb 04 '19 at 20:25
  • @Michael I tried your code but fail to reproduce. However, according to your screenshot above, the controller is able to bind the model automatically. Usually that means the 415 is thrown within the action or the process of JSON serialization. I think it's better to share us how you create the response within the controller action. – itminus Feb 05 '19 at 03:30
  • @itminus when I hit the break point in the screen shot which is still in the very beginning of the method, I stop go back to the browser and it already says 415. That tells me from your statement that it must be something in the process of JSON serialization. I just wish I knew more about that process. I can share the controller logic if you really think it has anything to do with it. – Michael Feb 05 '19 at 16:22
  • @ChrisPratt At one point I did try to add a custom formatter nuget package but backed it out after I didn't like it. – Michael Feb 05 '19 at 16:30
  • Well, something is messed up there. Essentially, you issue is that there's no JSON input formatter registered, so your app is rejecting the application/json content type. – Chris Pratt Feb 05 '19 at 16:34
  • @ChrisPratt I created an MVC 5 project that is not .net core and this worked with no issues. I think .net core has a bug in it. – Michael Feb 05 '19 at 22:35

0 Answers0