jQuery AJAX를 사용하여 MVC 컨트롤러에 객체 배열 보내기
jQuery의 ajax()
메서드를 사용하여 객체 배열을 MVC 컨트롤러로 보낼 때 일반적인 문제는 컨트롤러의 배열에 대한 null
값을 받는 것입니다. 이는 컨트롤러 매개변수가 List<T>
.
이 솔루션에는 두 가지 주요 조정이 포함됩니다.
JSON 데이터 유형 지정: ajax()
호출은 contentType
및 dataType
을 모두 'application/json; charset=utf-8'
으로 명시적으로 설정해야 합니다.
JSON.stringify()를 사용하여 데이터 직렬화: 객체의 JavaScript 배열은 JSON.stringify()
을 사용하여 JSON 문자열로 변환해야 합니다. 결정적으로, 이 문자열은 속성(예: '사물') 내에 배열을 캡슐화해야 합니다.
다음은 이러한 변경 사항을 구현하는 수정된 코드입니다.
<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 called.'); }, error: function (response) { $('#result').html(response.responseText); // Display error details } }); });</code>
해당 C# 컨트롤러 메서드:
<code class="language-csharp">public void PassThings(List<Thing> things) { // Access the 'things' array here } public class Thing { public int Id { get; set; } public string Color { get; set; } }</code>
이 단계를 따르면 jQuery AJAX를 통해 객체 배열을 MVC 컨트롤러 메서드로 성공적으로 전송할 수 있습니다. 더 나은 오류 처리를 위해 AJAX 호출에서 failure
에서 error
으로 변경하고 디버깅 목적으로 응답 텍스트를 표시합니다.
위 내용은 jQuery AJAX를 사용하여 객체 배열을 MVC 컨트롤러에 전달하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!