2015-01-09 63 views
1

我想弄清楚如何從我的表單發佈對象到web api服務。在我的控制器中,我定義了一個我想添加輸入值的模型。如何發佈對象到WebAPI

$scope.Label; 

我的輸入字段內我有他們使用結合ng-model如:

<input type="checkbox" ng-model="label.isPublic" /> 
<input type="text" ng-model="label.labelName" required focus-me /> 

在提交表單這兩個字段一個傳遞給我服務的,並提交給我的WebAPI

我曾嘗試過兩種方式提交此文件:

function addLabel(label) { 
     var mylabel = encodeURIComponent(angular.toJson(label)); 
     return $http.post('reportLibrary/createlabel/', { params: label }, { 

     }).then(function (response) { 
      return response.data; 
     }); 
    }; 

和als O作爲不宣參數

function addLabel(label) { 
     var mylabel = encodeURIComponent(angular.toJson(label)); 
     return $http.post('reportLibrary/createlabel/', label , { 

     }).then(function (response) { 
      return response.data; 
     }); 
    }; 

在的WebAPI我對後一方法設置如下

[Route ("reportLibrary/createlabel/")] 
     [HttpPost] 
     public DTOs.ReportLabel CreateLabel(DTOs.ReportLabel json) 
     { 
      DTOs.ReportLabel result = new DTOs.ReportLabel(); 

     //.... do stuff 
      return result; 
     } 

的ReportLabel(DTO)的定義如下:

public class ReportLabel 
{ 
    public Int64 LabelId { get; set; } 
    public string LabelName { get; set; } 
    public bool IsPublic { get; set; } 
    public IEnumerable<Report> Reports { get; set; }//placeholder? 

} 

的問題我有,當我從我的角度服務發佈一個對象時,它在API中顯示爲空。如果將方法中的類型更改爲JToken或JObject之類的值,則會顯示值。

任何人都可以幫助我理解爲什麼當我定義它不是從角度傳遞的類型?

謝謝

回答

1

看起來好像你可能正在做一個額外的步驟。你不需要在JSON編碼再通過在JSON

return $http.post('reportLibrary/createlabel/', { LabelId: 101, LabelName: 'myname' }, { 

然後

public DTOs.ReportLabel CreateLabel([FromBody]ReportLabel reportLabel) 

在網絡價值會通過看一看,你應該在調試工具看到或招潮蟹實際發佈值(表單值)。

+0

這確實有效,但這似乎有點沉重。如果我有一個有10或20個屬性的對象呢?似乎應該有一種方法來傳遞對象,聲明和設置每個屬性/字段。我很樂意看到其他選項 – rlcrews 2015-01-10 12:12:58

+0

我的擔心並不是那麼重,它很沉重,但感覺像魔術一樣。 Microsoft試圖通過查找如何傳遞數據然後嘗試映射到它來簡化它。我從來沒有通過傳遞參數取得很大的成功,但我知道這是可能的。當我想完全控制我使用窗體集合(我發佈在這裏:http://peterkellner.net/2013/08/18/collection-form-post-parameters-in-webapi-controller/) – 2015-01-10 15:36:02