使用 jQuery Ajax 将对象数组发送到 MVC 控制器
使用 jQuery 的 ajax()
方法将对象数组发送到 MVC 控制器时,控制器的参数可能会收到 null
值。本文概述了解决方案。
空值故障排除
问题通常源于不正确的数据序列化和内容类型处理。 解决方法如下:
设置内容类型和数据类型:
ajax()
函数需要明确的 contentType
和 dataType
设置:
<code class="language-javascript">contentType: 'application/json; charset=utf-8', dataType: 'json',</code>
JSON 序列化:
对象数组必须使用JSON.stringify()
序列化为JSON格式。 像这样构造数据:
<code class="language-javascript">things = JSON.stringify({ things: things });</code>
说明性示例
此示例演示如何成功传递对象数组:
<code class="language-javascript">$(document).ready(function() { const things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; const data = JSON.stringify({ things: things }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Home/PassThings', data: data, success: function() { $('#result').html('"PassThings()" successfully executed.'); }, error: function(response) { $('#result').html(response.responseText); // Display error details } }); });</code>
对应的控制器方法(C#示例):
<code class="language-csharp">public void PassThings(List<Thing> things) { // Process the 'things' list here }</code>
请记住将 /Home/PassThings
替换为您的实际控制器和操作。 使用 error
代替 failure
可以提供更多信息的错误处理。 这种修改后的方法可确保正确的数据传输并防止null
值问题。
以上是如何使用 jQuery Ajax 正确地将对象数组传递到 MVC 控制器?的详细内容。更多信息请关注PHP中文网其他相关文章!