【问题标题】:Getting JSON in Post Method [duplicate]在 Post 方法中获取 JSON [重复]
【发布时间】:2014-01-23 11:25:35
【问题描述】:

我在 MVC5 中使用 c# 和 我以 JSON 格式将数据发布到 Web-api2 服务器,如下所示:

function SendSms() {
    var studentData = {
        Id: "4",
        ClientId: "2",
        NoOfRecipient: "3",
        Msg: "This is a test",
        Numbers: [
            { Number: "988888888", Id: "3"},
            { Number: "988888787", Id: "5"}
        ]
    };
    console.log(JSON.stringify(studentData));

    $.ajax({
        cache: false,
        type: "POST",
        url: "http://localhost/ProductsApp/api/SmsClients",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(studentData),
        dataType: "json",
        processData: true,
        success: function (data, status, jqXHR) {
           console.log(data);
        },statusCode: {
            201 /*Created*/: function (data) {
               console.log("created");
            }
        }
    })
    .fail(
    function (xhr, textStatus, err) {
        console.log("Error");
    });
}

并像这样接受 JSON:

public HttpResponseMessage Post(SmsData smsData)
{
    //code to be performed after getting Post
}

而我的 SmsData 模型是这样的:

public class SmsData
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public int NoOfRecipient { get; set; }
    public List<Numbers> Numbers { get; set; }
    public string Msg { get; set; }
    public DateTime SentDate { get; set; }
}

public class Numbers{
    public int Id { get; set; }
    public long Number { get; set; }
}

但是我得到了 smsData Null 的 Numbers 属性。为什么会这样...为什么 Numbers 属性会为空。我怎样才能得到数字

【问题讨论】:

  • 您是否尝试过在 Numbers 字段中使用数组而不是列表?
  • 我相信 'List' 不适用于 Json 解析器。尝试将其更改为 'Numbers[] Numbers'

标签: c# asp.net-mvc json post asp.net-web-api2


【解决方案1】:

使用数组而不是列表应该会有所帮助,但您也可以在执行 ajax 调用时尝试设置“traditional:true”参数。

$.ajax({ 缓存:假, 传统:真实, 类型:“POST”,

【讨论】:

    猜你喜欢
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多