Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

前端 未结 13 1587
逝去的感伤
逝去的感伤 2020-11-22 14:22

I\'m trying to pass an array of objects into an MVC controller method using jQuery\'s ajax() function. When I get into the PassThing() C# controller method, the argument \"t

相关标签:
13条回答
  • 2020-11-22 14:28

    Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

    $(document).ready(function () {
        var things = [
            { id: 1, color: 'yellow' },
            { id: 2, color: 'blue' },
            { id: 3, color: 'red' }
        ];      
    
        things = JSON.stringify({ 'things': things });
    
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Home/PassThings',
            data: things,
            success: function () {          
                $('#result').html('"PassThings()" successfully called.');
            },
            failure: function (response) {          
                $('#result').html(response);
            }
        }); 
    });
    
    
    public void PassThings(List<Thing> things)
    {
        var t = things;
    }
    
    public class Thing
    {
        public int Id { get; set; }
        public string Color { get; set; }
    }
    

    There are two things I learned from this:

    1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

    2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

    I hope this helps someone else!

    0 讨论(0)
  • 2020-11-22 14:30

    I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.

    In my case the solution was as follows:

    Script - stringify the original array (without using a named property)

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: mycontrolleraction,
            data: JSON.stringify(things)
        });
    

    And in the controller method, use [FromBody]

        [HttpPost]
        public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
        {
            return Ok();
        }
    

    Failures include:

    • Naming the content

      data: { content: nodes }, // Server error 500

    • Not having the contentType = Server error 500

    Notes

    • dataType is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).
    • List<Thing> also works in the controller method
    0 讨论(0)
  • 2020-11-22 14:35

    Couldn't you just do this?

    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];
    $.post('@Url.Action("PassThings")', { things: things },
       function () {
            $('#result').html('"PassThings()" successfully called.');
       });
    

    ...and mark your action with

    [HttpPost]
    public void PassThings(IEnumerable<Thing> things)
    {
        // do stuff with things here...
    }
    
    0 讨论(0)
  • 2020-11-22 14:35

    If you are using ASP.NET Web API then you should just pass data: JSON.stringify(things).

    And your controller should look something like this:

    public class PassThingsController : ApiController
    {
        public HttpResponseMessage Post(List<Thing> things)
        {
            // code
        }
    }
    
    0 讨论(0)
  • 2020-11-22 14:37

    This is how it works fine to me:

    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];
    
    $.ajax({
        ContentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Controller/action',
        data: { "things": things },
        success: function () {
            $('#result').html('"PassThings()" successfully called.');
        },
        error: function (response) {
            $('#result').html(response);
        }
    });
    

    With "ContentType" in capital "C".

    0 讨论(0)
  • 2020-11-22 14:40

    The only way I could get this to work is to pass the JSON as a string and then deserialise it using JavaScriptSerializer.Deserialize<T>(string input), which is pretty strange if that's the default deserializer for MVC 4.

    My model has nested lists of objects and the best I could get using JSON data is the uppermost list to have the correct number of items in it, but all the fields in the items were null.

    This kind of thing should not be so hard.

        $.ajax({
            type: 'POST',
            url: '/Agri/Map/SaveSelfValuation',
            data: { json: JSON.stringify(model) },
            dataType: 'text',
            success: function (data) {
    
        [HttpPost]
        public JsonResult DoSomething(string json)
        {
            var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
    
    0 讨论(0)
提交回复
热议问题