2017-06-16 91 views
1

使用下面的代碼,我能夠將這種內容傳遞給我的WebAPI 接收它像JSON.stringify數據/子數據要發送到的WebAPI

public void Post(Business.Entities.api.newsalert alert) 
{ 
    //do stuff here 
} 

category = $('#dt_category').val(); 
title = $('#inputTitle').val(); 
url = $('#inputURL').val(); 
comments = $('#inputComments').val(); 
subject = "News Alert/Alerte Nouvelles: " + title; 

var dataJSON = { 
    userid: username, 
    to: "[email protected]", 
    url: url, 
    subject: subject, 
    title: title, 
    source: "My company", 
    comments: comments, 
    category: category 
}; 

$.ajax({ 
    type: 'POST', 
    url: "http://mywebserver/api/NewsAlerts", 
    data: JSON.stringify(dataJSON), 
    contentType: 'application/json; charset=utf-8', 
    success: function (data) { 
     q.resolve(); 
    } 
}); 

然而,我的老闆問我讓類別中選擇使用多個..

所以我做了這個

category = $('#dt_category').val(); //apples, oranges, peaches 
    title = $('#inputTitle').val(); 
    url = $('#inputURL').val(); 
    comments = $('#inputComments').val(); 
    subject = "News Alert/Alerte Nouvelles: " + title; 

    var categories = []; 
    $(category).each(function (index) { 
     categories.push({ 'category': category[index] }); 
    }); 

    var dataJSON = { 
     userid: username, 
     to: "[email protected]", 
     url: url, 
     subject: subject, 
     title: title, 
     source: "My company", 
     comments: comments, 
     category: categories 
    }; 

    $.ajax({ 
     type: 'POST', 
     url: "http://mywebserver/api/NewsAlerts", 
     data: JSON.stringify(dataJSON), 
     contentType: 'application/json; charset=utf-8', 
     success: function (data) { 
      q.resolve(); 
     } 
    }); 

但是,當我的WebAPI收到Ajax的說,它始終爲空。我假設我需要以某種方式將類別變成某種子節點,但我不確定。

+1

是你的模型'Business.Entities.api.newsalert'期待一個列表? 含義'Business.Entities.api.newsalert.Category'是'typeof列表' – Munzer

+1

你可以嘗試改變'category'數據類型爲'List ' –

+0

Duh,沒有考慮過我的業務對象可能是問題,只是假設它將是json序列化。請看看,thx。 –

回答

1

你的api請求對象應該包含一個屬性,該屬性是屬性爲「category」的類的一些集合類型。

public class newsalert 
{ 
    //Other Properties   

    [JsonProperty(PropertyName = "category")] 
    IList<Category> Categories {get;set;} 
} 

public class Category 
{ 
    public string category {get;set;} 
}