2013-10-10 15 views
3

出於某種原因,我無法使ServiceStack序列化發佈(serializeArray)表單數據。 發佈的JSON是:將表單序列化爲ServiceStack的數組

{"somestuff":"someData","formInput":[{"name":"1","value":"2"},...]} 

jQuery的我使用後我的表格:

var formData = $("form").serializeArray(); 
      var data = { 
       someOtherFields: some data, 
       formInput: formData 
      }; 
      $.ajax({ 
       type: "post", 
       url: "/api/location", 
       data: data, 
       dataType: "json", 
       success: function(response) { 
        if (response.status == "success") { 
         scope.showForm = false; 
         scope.status = "successfully added message"; 
        } else { 
         scope.status = response.message; 
        } 
       } 
      }); 

這是張貼到ServiceStack服務與DTO:

public class ServiceRequest 
{ 
    other atributes; 
    public List<ArraySerializeResult> FormInput { get; set; } 
} 

public class ArraySerializeResult 
{ 
    public string Name { get; set; } 
    public string Value { get; set; } 
} 

其他屬性序列化正常,但formInput被序列化爲具有正確數量的元素的列表,但所有Name和Value對都爲null。

回答

2

SerivceStack期待你send your complex type格式化在JSV而不是JSON

您可以用JSV而不是JSON格式化請求,類似於ServiceStack項目中的JSV.js,或者實現您自己的Request Binder以反序列化JSON。

public override void Configure(Container container) 
{ 
    RequestBinders.Add(typeof (ServiceRequest), (IHttpRequest httpReq) => { 
     var myRequest = new ServiceRequest(); 
     // Deserialize the request here using ServiceStack.Text or whatever you like... 
     return myRequest; 
    }); 
} 
1

您應該向您的ajax請求添加「contentType」選項。隨着內容類型 「應用/ JSON」,servicestack可以desirialize JSON數組

contentType: "application/json; charset=utf-8" 

所以它看起來像這樣

 $.ajax({ 
      type: "post", 
      url: "/api/location", 
      data: data, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(response) { 
       if (response.status == "success") { 
        scope.showForm = false; 
        scope.status = "successfully added message"; 
       } else { 
        scope.status = response.message; 
       } 
      } 
     });