【问题标题】:JSON.stringify data/child data in order to send to webapiJSON.stringify 数据/子数据以便发送到 webapi
【发布时间】:2017-11-19 16:27:58
【问题描述】:

使用下面的代码,我可以将此内容传递给我的 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: "me@here.com",
    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: "me@here.com",
        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 Put 时,它始终为 null。我假设我需要以某种方式将类别制作成某种子节点,但我不确定。

【问题讨论】:

  • 您的模特Business.Entities.api.newsalert 期待一份清单吗?意思是Business.Entities.api.newsalert.Categorytypeof List<int>
  • 您可以尝试将category 数据类型更改为List<string>
  • 呃,没有考虑到我的业务对象可能是问题,只是假设它是 json 序列化。会看看的,谢谢。

标签: c# jquery json ajax asp.net-web-api


【解决方案1】:

您的 api 请求对象应包含一个属性,该属性是具有“类别”属性的类的某种集合类型。

public class newsalert
{
     //Other Properties         

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    相关资源
    最近更新 更多