Andy Stannard
Andy Stannard

Reputation: 1703

Having issues Deserialising a JSON model in controller

I have the following C# Models but they do not get the Id or AssigneeId populated from the JSON any help please?:

public class AssignModel
{
    [Required]
    public Guid Id { get; set; }
    public bool Clear { get; set; }
    public string AssigneeId { get; set; }
}

public class MassAssignModel
{
    [Required]
    public List<AssignModel> Tickets { get; set; }
} 


public ActionResult MassAssign(MassAssignModel model)
{
    //DO stuff here
}

I am try to have these populated by deserialising JSON but it never get the values. Here is my javascript, the first method call is massAssign():

function massAssign() {
    assignTicketsTo(getSelectedTicketsIds());
}

function getSelectedTicketsIds() {
    var tickets;
    var selected = $('.selected-ticket:checked');
    tickets = selected.map(function () {
    return { Id: this.value, AssigneeId: "COMPONENTS\ASTANNARD", Clear:false };
    }).get();

    return tickets;
}

function assignTicketsTo(selectedTicketsIds) {

    var postdata = JSON.stringify({
        Tickets: [selectedTicketsIds]
    });

    $.ajax({
    url: Helper.Util.action({ controller: "Ticket", action: "MassAssign" }),
    dataType: 'json',
    data: postdata,
    type: 'post',
    success: function (data, textStatus, jqXHR) {

    },
    error: function (jqXHR, textStatus, errorThrown) {
        $("#load_tickets").hide();
        Helper.alert(errorThrown);
    }
});

}

Upvotes: 0

Views: 53

Answers (1)

nemesv
nemesv

Reputation: 139758

If you want to send JSON to an MVC controller you need to set the contentType to 'application/json' in your $.ajax:

$.ajax({
    url: Helper.Util.action({ controller: "Ticket", action: "MassAssign" }),
    dataType: 'json',
    contentType: 'application/json',
    data: postdata,
    type: 'post',
    success: function (data, textStatus, jqXHR) {

    },
    error: function (jqXHR, textStatus, errorThrown) {
        $("#load_tickets").hide();
        Helper.alert(errorThrown);
    }

dataType is for

The type of data that you're expecting back from the server.

You have one additional problem with your code, when you are creating the postdata the selectedTicketsIds variable already contains an array so you don't need to wrap it again with [selectedTicketsIds].

So change your postdata to:

var postdata = JSON.stringify({
        Tickets: selectedTicketsIds
});

Upvotes: 1

Related Questions