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

前端 未结 13 1805
逝去的感伤
逝去的感伤 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: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 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 also works in the controller method

提交回复
热议问题