2016-09-23 2 views
1

모델 개체 목록을 사용하여 테이블을 만들었습니다. 그런 다음 해당 행의 버튼을 클릭하면 행 데이터가 Ajax 게시물에 전달됩니다.mvc 컨트롤러에 전달 된 null JSON 문자열을 해결하는 방법?

Ajax 포스트 내에서 .stringify은 데이터가 전달 된 행에서 호출됩니다.

["66", "[email protected]", "2009", "test",…] 
0 
: 
"66" 
1 
: 
"[email protected]" 
2 
: 
"2009" 
3 
: 
"test" 

을하지만 클라이언트 측에서 호출되는 컨트롤러 POST 액션으로 단계 때 내가 개발 도구의 와이어에 전달 된 데이터의 값을 확인할 때 나는 그들이이 채워지는 것을 볼 수 있습니다. 예상되는 JSON 문자열은 null/empty입니다. 제 생각에 이것은 stringify가 배열의 각 값과 연결할 속성 이름을 가지고 있지 않을 수도 있습니다.

질문 :

어떻게 MVC 컨트롤러에 전달 널 JSON 문자열을 해결할 수 있습니까?

public class Status 
{ 

     [Key] 
     public int ID { get; set; } 


     public string Contact_Email { get; set; } 

     public string RID { get; set; } 

     public string Name { get; set; } 



    } 

테이블 및 AJAX 포스트 방법 :

 <table id="statusTable" class="table table-hover table-bordered results"> 
      <thead> 
       <tr> 
        <th>ID</th> 
        <th>Email</th> 
        <th>RID</th> 
        <th>Name</th> 
        <th>Update Record</th> 


       </tr> 
      </thead> 
      <tbody> 
      @foreach (var row in Model.ReleaseStatus) 
      { 
        <tr> 
         <td>@Html.Raw(row.ID)</td> 
         <td>@Html.Raw(row.Contact_Email_Name)</td> 
         <td>@row.RID</td> 
         <td>@row.Name</td> 
         <td><button type="submit" class="btn btn-success">Update</button></td> 
        </tr> 
       } 
      </tbody> 

     </table> 



$(".btn-success").click(function() { 
      var $td = $(this).closest('tr').children("td"), 
      len = $td.length; 
      var tableData = $td.map(function (i) { 
       if (i < len - 1) 
        return $(this).text(); 
      }).get(); 

      console.log(tableData); 

      //Post JSON data to controller 
      $.ajax({ 
       type: "POST", 
       url: 'updateStatus', 
       data: JSON.stringify(tableData), 
       contentType: "application/json; charset=utf-8", 
       success: function (response) { 
        console.log("post success"); 
       }, 
       error: function (request) { 
        console.log("post error" + request.error); 
       } 

      }); 


     }); 

그리고 MVC 제어기 최종적 POST 방법 :

모델 - 여기서

아래 구현의 요지 인
[HttpPost] 
    public ActionResult updateStatus(stirng jsonString) 
    { 
     //deserialise the json to a Status object here 
    } 
+2

왜 당신이하려고하는

아약스 호출에서 다음
var statusData = { ID:tableData[0], Contact_Email:tableData[1], RID:tableData[2], Name:tableData[3] }; 

,

data: JSON.stringify(statusData), 

+0

mvc 액션에서 onject를 지정하려고 시도했으나,이 메소드는 'public ActionResult updateStatus (Status model)'및 'var data = {ID : 66, Contact_Email :'[email protected] ' updateStatus (Status vm)와 마찬가지로 객체는 게시물 동안 null입니다. 주요 문제는 jquery에서 전달되는 데이터에 값에 첨부 된 이름이 없다는 것입니다. –

+0

예, 이전에 언급 한대로 생성하고 객체를 생성해야하고 ajax에서'contentType : "application/json; charset = utf-8",'data : data, '를 사용해야하는 이유는 무엇입니까? –

답변

6

json 문자열이 아닌 실제 객체를 사용하려면 컨트롤러를 만들어야합니다. 이로써

은 내가

[HttpPost] 
public ActionResult updateStatus(stirng jsonString) 
{ 
    //deserialise the json to a Status object here 
} 

당신이 당신의 ViewModel을 복제하는 JSON 개체를 전달해야 Status에 JSON을 결합하는 모델 바인더 위해서는

[HttpPost] 
public ActionResult updateStatus(Status vm) 
{ 
    //no need to deserialize - was already done by the model binder 
} 

수 있어야 의미한다. 의사 코드에서

{ 
ID:yourId, 
Contact_Email:yourContactEmail, 
RID:YourRID, 
Name:yourName 
} 

, 당신은 할 수 :

[HttpPost] 
public ActionResult updateStatus([FromBody]Status status) 
{ 
    //add the serialize attribute on your model 
} 
+0

그러나 더 좋은 설명을 더 잘 만들 것입니다 – Fabjan

+1

OP는 또한 배열을 다시 게시하는 대신보기에서 객체를 올바르게 생성하지 않는 한 아무 것도하지 않습니다. –

+1

json 문자열 앞에 Status 객체를 전달하려고 시도했지만 액션 메소드에 도달하면 객체가 null입니다. 내 데이터가 각 값에 대해 이름을 지정하지 않았기 때문에 그것이라고 생각합니까? –

-2

몸 속성에서에게 시도 모델 대신에`string`에 바인드 할 수 있습니다.
관련 문제