sojim2
sojim2

Reputation: 1307

JSON not getting passed to controller via JQuery

I can't seem to get the json (verified valid) to the UpdateCaps controller from ListBox:

Controller:

public IActionResult UpdateCaps(List<SelectListItem> selectedItems)
{
    var test = selectedItems;
    return Json(test);
}

ListBox:

   @(Html.Kendo().ListBox()
        .Name("selected")
        .ConnectWith("optional")
        .Selectable(ListBoxSelectable.Multiple)
        .DropSources("optional")
        .DataTextField("Description")
        .DataValueField("Id")
        .Toolbar(toolbar =>
        {
            toolbar.Position(ListBoxToolbarPosition.Right);
        })
        .DataSource(source => source
            .Custom()
            .Type("aspnetmvc-ajax")
            .Transport(transport => transport
                .Read(read => read.Action("GetSelectedCapsUnits", "OrgStructure").Data("level1Select"))
            )
        )
        .Events(events => events
            .Add("onAdd")
            .Remove("onRemove")
        )
        .BindTo(new List<SelectListItem>())
    )

The onAdd in the listbox triggers this javascript:

function onAdd(e) {
    console.log(e.dataItems);
    console.log(JSON.stringify({ selectedItems: e.dataItems }))
    $.ajax({
         type: "POST",
         url: "/OrgStructure/UpdateCaps",
         contentType: "application/json; charset=utf-8",
         data: JSON.stringify({ selectedItems: e.dataItems }),
         dataType: "json",
         success: function (result) {
          alert("Successfully sent to server: " + result.map(function (x) {
                 return x.Text
             }))
         }
     });

    $('#selectedListBox').text(' ' + e.dataItems.length + " added - saved");  

}

Verified the JSON string is valid: enter image description here With: console.log(JSON.stringify({ selectedItems: e.dataItems }))

It fires the UpdateCaps method onAdd but no results: enter image description here

Upvotes: 1

Views: 52

Answers (1)

Modify this line of code:

JSON.stringify({ selectedItems: e.dataItems }),

to

JSON.stringify(e.dataItems),

The problem is that you are sending back to the controller an object which contains a property named selectedItems which holds a list of objects. You have to pass the list instead.

Based on your comment, you do not need a List<SelectListItem> as parameter.

Create the following class:

public class MyModel
{
    public int Id { get; set; }
    public string Description { get; set; }
}

and update your code to expect a list of MyModel:

public IActionResult UpdateCaps([FromBody]List<MyModel> models)

Upvotes: 1

Related Questions