2017-02-01 7 views
-3

배열 객체를 자바 스크립트에서 컨트롤러로 전달하고 싶습니다. 그것은 최대 경고를 체크 박스 값을 제공하므로 자바 스크립트에서 잘못된 건 없다고 생각합니다. 컨트롤러에서 객체는 항상 null입니다. 내가 여기서 뭘 잘못 했니?배열 객체를 웹 서비스 컨트롤러에 전달하려고하지만 항상 null

function amal() { 

var selected = []; 

$('input[type="checkbox"]:checked').each(function() { 

    selected.push($(this).val()); 
}); 
alert(selected); 

$.ajax({ 
    url: "http://localhost:63138/api/Emptbles/LoadAmal", 
    type: "POST", 
    data: selected, 

    contentType: "application/json", 
    success: function (response) { 
     alert("success"); 
     myFunction(); 
    }, 
    error: function() { 

    } 
}); 

내 API 컨트롤러

[HttpPost] 
    public IHttpActionResult LoadAmal(List<selectedSymptoms>list) 
    { 
     string item1 = ""; 
     string item2 = ""; 
     string item3 = ""; 


     for (int i = 0; i < list.Count; i += 3) 
     { 
      //grab 3 items at a time and do db insert, 
      // continue until all items are gone.. 
      item1 = list.ElementAt(i+0).ToString(); ; 
      item2 = list.ElementAt(i + 1).ToString(); ; 
      item3 = list.ElementAt(i + 2).ToString(); ; 
      // use the items 
     } 

     string query = "EXEC Add_Employee'" + item1 + "','" + item2 + "','" + item3 + "'"; 

     int result = connectionProvider.CreateSomething(query); 


     return Ok(result); 
} 

내 selectedSymptoms 클래스 (난 그냥 컨트롤러에 제이슨 객체를 먹고 싶어,이 적합한 지 여부를 잘 모릅니다. 감사합니다)

public class selectedSymptoms 
{ 
    public void PassThings(List<selectedSymptoms> symtoms) 
    { 
     var t = symtoms; 
    } 


} 
+1

필요가'selectedSymptoms' 어떻게 생겼는지보고 :

API는 같을 것이다. 객체는 동일한 속성을 공유해야하므로 serializer가 요청의 속성을 매핑 할 수 있습니다. 이 유형이'List '(또는 다른 단순 유형) ​​인 경우 다를 수 있습니다. –

+0

주석에 글을 올리는 코드가 작동하지 않습니다. 질문을 수정해야합니다 –

+0

@ 마크 나는 rqquested 클래스를 추가했습니다. 좀 봐 주시겠습니까? – Amal

답변

-1

시도 이 :

data: { 'list' : selected } 
0

실행중인 시나리오는 전송하는 객체와 웹 API 사이의 직렬화 문제입니다. Microsoft gives you code to test this process, 나는 당신에게 많은 것을 가르쳐주기 때문에 사용을 추천합니다. 당신은 아마 같을 것이다 응답에 보내는 어떤

는 :

["someValue1", "someValue2", "etc"] 

당신의 API의 Type는 직렬화 할 필요가 있으며, 현재 클래스를 주어 그 일을 전혀 가능한 방법이 없습니다. 원하는 모든 작업을 문자열 목록으로 보내려면 복잡한 객체를 사용하지 말고 단순히 List<string>을 사용해야합니다. 실제로 복잡한 객체를 사용하려면 데이터를 매핑 할 속성이 필요합니다. 당신은 우리가 기본적를 작성하는 방법을 볼 수 있습니다

var people = []; 

$('input[type="checkbox"]:checked').each(function() { 
    var Person = new Object(); 
    Person.Name = $(this).val(); 
    people.push(Person); 
}); 

$.ajax({ 
    url: "http://localhost:63138/api/Emptbles/LoadAmal", 
    type: "POST", 
    data: people, 
    contentType: "application/json", 
    success: function (response) { 
    }, 
    error: function() { 
    } 
}); 

: I 클래스

public class Person 
{  
    public string Name {get; set;} 
} 

을했다 그리고 난 그 자바 스크립트 객체 표현을 게시하고 싶었다면

, 내 코드는 같을 것이다 C# 클래스의 JavaScript 버전의 배열이며 두 객체간에 Name 속성을 쉽게 매핑 할 수 있습니다.

public IHttpActionResult GetStuff(List<Person> peeps) {}