jQuery Ajax를 사용하여 MVC 컨트롤러 메서드에 객체 배열 전달
jQuery의 ajax() 함수를 사용하여 MVC 컨트롤러의 메서드에 객체 배열을 전달하려고 할 때 컨트롤러 메서드의 "things" 매개변수가 비어 있는 상황이 발생할 수 있습니다. 이 문제는 List를 매개변수 유형으로 사용하는 경우에도 발생할 수 있습니다.
이 문제의 해결 방법은 다음과 같습니다.
things = JSON.stringify({ 'things': things });
이 방법으로 JSON 개체에 "사물" 배열을 래핑하면 해당 배열을 컨트롤러 메서드에 성공적으로 전달할 수 있습니다.
이 구현의 전체 코드는 다음과 같습니다.
$(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.'); }, error: function (response) { $('#result').html(response.responseText); // 使用 response.responseText 获取错误信息 } }); });
public void PassThings(List<Thing> things) { // 处理things数据 } public class Thing { public int Id { get; set; } public string Color { get; set; } }
이 구현의 두 가지 중요한 측면에 유의하세요.
contentType: 'application/json; charset=utf-8', dataType: 'json',
JSON.stringify({ 'things': things }) ``` 并且在`failure`回调函数中,使用 `response.responseText` 获取服务器返回的错误信息,以更准确地处理错误。 通过以上步骤,您可以确保将对象数组正确地传递给您的MVC控制器。
위 내용은 jQuery Ajax를 사용하여 객체 배열을 MVC 컨트롤러에 성공적으로 전달하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!