2013-01-14 2 views
0

json을 MVC4의 객체로 비 직렬화하려고하면 문제가 발생합니다. 내가 모델을 얻을 Json.netJson 비 직렬화 MVC 4 녹아웃 j

var Vm = function(data) { 
     var self = this; 

     ko.mapping.fromJS(data, {}, self); 

     self.GetResults = function() { 
      $.ajax({ 
       type: "POST", 
       url: '@Url.Action("Action", "Controller")', 
       data: ko.mapping.toJSON(self), 
       success: function(data) { 
        alert('OK'); 
       } 
      }); 
     }; 
    }; 

    var viewModel = new Vm(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))); 
    ko.applyBindings(viewModel); 

내가 컨트롤러의 동작 GetResults를 호출 할 때 내 문제를 사용하여 객체를 직렬화보기에

public class TestViewModel 
{ 
    public string Code { get; set; } 

} 

:

나는 ViewModel에 있습니다 , 모든 속성은 null입니다.

내 JSON은 다음과 같습니다

{"Code":"TestCode"} 

가 나는 MVC3 프로젝트에서 동일한 구조를 가지고 잘 작동합니다. MVC4에서 뭔가 빠졌어?

건배!

+0

Fiddler를 사용하여 요청 및 응답의 모양을 확인해 보셨습니까? – Rich

+0

예, 요청이 정상적으로 보입니다. Content-Type이 있습니다. application/json 수락 : application/json, text/javascript, */*; q = 0.01이고 질문에있는 json ("Code": "TestCode") – estebane97

답변

1

일부 시나리오에서는 jQuery가 데이터를 요청의 양식에 포함시키는 것으로 나타났습니다. 이 경우 값은 Controller 메소드의 오브젝트 유형에 자동으로 맵핑되지 않습니다.

1) 데이터가 직렬화 있는지 확인합니다 :

이 해결하기 위해, 두 가지 작업을 수행해야합니다. 나는이 작업을 수행 할 수있는 쉬운 방법을 발견하고 확장 방법을 덤프 : IsDataSerialized가 true를 돌려

public static class WebContextExtensions 
{ 
    public static bool IsDataSerialized(this HttpContext context) 
    { 
     return context.Request.Params.AllKeys[0] == null; 
    } 
} 

2) 경우, 당신이 당신의 객체 타입으로 데이터를 역 직렬화 할 필요가있다.

public class GenericContextDeserializer<T> where T : new() 
{ 
    public T DeserializeToType(HttpContext context) 
    { 
     T result = new T(); 
     if (context != null) 
     { 
      try 
      { 
       string jsonString = context.Request.Form.GetValues(0)[0].ToString(); 
       Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer(); 
       result = js.Deserialize<T>(new Newtonsoft.Json.JsonTextReader(
           new System.IO.StringReader(jsonString))); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
     } 
     else 
      throw new NullReferenceException(); 
     return result; 
    } 
} 
이제

당신의 컨트롤러 방법에 모두 함께 넣어 : 우리는뿐만 아니라 것을 할 수있는 GenericDeserializer 방법을 쓴 당신은 자세한 내용을 원하는 경우

[HttpPost] 
[HttpOptions] 
public HttpResponseMessage MyAction(JsonData data) 
{ 
    var results = Request.CreateResponse(); 
    try 
    { 
     data = new GenericContextDeserializer<JsonData>().DeserializeToType(HttpContext.Current); 
     // do stuff with data 
     results.StatusCode = HttpStatusCode.OK; 
    } 
    catch (Exception ex) 
    { 
     results.StatusCode = HttpStatusCode.InternalServerError; 
    } 
    return results; 
} 

, 내가 쓴 a blog post 년 하반기의 .