Click here to Skip to main content
15,917,618 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello experts
I have a list from movie.js file, I want to send my list to HomeController in Passthings function. But when I use a breakpoint on the PassThings function, I notice that the list(i mean,I do not receive this list in my function that I send from the javascript file ) in PassThings function is empty.
This is the code of my movie.js file:
function fun1() {
    $(document).ready(function () {
        var things = [
            { id: 1, color: 'yellow' },
            { id: 2, color: 'blue' },
            { id: 3, color: 'red' }
        ];

        var thing = {
            ThingList : things
        }

        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: '/Home/PassThings',
            data: thing,
            success: function () {
                $('#result').html('"PassThings()" successfully called.');
            },
            failure: function (response) {
                $('#result').html(response);
            }
        });
    });

}

SaveBtn.addEventListener('click', fun1);


and here is my Home/Passthings Action:
public void PassThings(List<Thing> things)
{
    var t = things;
}

and here is my model :
public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

and in the my Index.cshtml i use this to call my movie.js file :
<pre>
<div class="col-6 col-md-3">
    <button type="submit" id="SaveBtn" class="btn btn-primary form-control">Save</button>
</div>
<script src="~/js/movie.js"></script>


What I have tried:

i tried with using [httpPost]
and i tried with IActionResult too :
[HttpPost]
    public IActionResult PassThings ([FromBody]IEnumerable<Thing> things)
    {
        return Ok();
    }
Posted
Updated 21-May-24 6:12am
v2
Comments
Rob Philpott 21-May-24 12:24pm    
Could it be that you are posting a ThingList which contains an array of things, but the controller is expecting an array of things, not a thinglist?
Max Speed 2022 21-May-24 19:24pm    
thanks alot <3 that's work

1 solution

Your controller is expecting a List<Thing>.

Your JavaScript is passing an object containing a single property, called ThingList, which contains a list of Thing objects.

The data you pass from JavaScript needs to match the data expected by the controller. Either remove the wrapper object from your JavaScript, or add a suitable wrapper class in your C#.
C#
public class ThingListModel
{
    public List<Thing> ThingList { get; set; }
}

[HttpPost]
public IActionResult PassThings (ThingListModel things)
{
    ...
}
 
Share this answer
 
Comments
Max Speed 2022 21-May-24 19:24pm    
thank you alot,that's work <3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900