使用jQuery Ajax在MVC中处理对象数组(PassThing()方法)
在MVC应用程序中,使用jQuery的ajax()函数将对象数组传递给控制器方法可能具有挑战性。PassThing()方法期望一个Thing对象的数组,但该数组以null的形式传入。
问题所在
提供的代码初始化了一个Thing对象的数组,并尝试使用JSON.stringify()将其传递给PassThing()方法。错误发生是因为发送到服务器的数据格式与PassThing()方法期望的格式不匹配。
解决方案
为了解决这个问题,使用JSON.stringify({ 'things': things }) 将数组转换为具有“things”属性的对象。此对象结构与PassThing()方法期望的参数相匹配。以下是修改后的jQuery代码:
<code class="language-javascript">$(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: '/Xhr/ThingController/PassThing', data: things }); });</code>
其他注意事项
为了确保数据成功传递:
以上是如何使用 jQuery Ajax 正确地将对象数组传递到 MVC 控制器?的详细内容。更多信息请关注PHP中文网其他相关文章!