在Asp.net MVC中获取post数组

时间:2014-01-23 10:16:00

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

我正在编写一个处理短信联系人的web api2程序。服务器上有一个JSON帖子,如下所示:

{
    "Id":"4",
    "ClientId":"2",
    "NoOfRecipient":"3",
    "Numbers":
    {
        "num1":9898776568,
        "num2":9087674589
    },
    "Msg":"This is a test"
}

并且在Server中我有一个类来处理这个JSON,如下所示:

public class SmsData
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public int NoOfRecipient { get; set; }
    public IEnumerable<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; }
}

[Table("SmsData")]
public class StoreSmsData
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public int NoOfRecipient { get; set; }
}

[Table("SmsSentNumbers")]
public class SentNumbers
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public long Numbers { get; set; }
    public int NumbersId { get; set; }
    public string Msg { get; set; }
    public DateTime SentDate { get; set; }
}

和控制器是:

public HttpResponseMessage Post(SmsData smsData)
{
    SmsHandler smsHandler = new SmsHandler();
    Clients client = smsHandler.GetClient(smsData.ClientId);
    if (client == null)
    {
        return Request.CreateResponse<SmsData>(HttpStatusCode.NotFound, smsData);
    }
    else if (smsData.NoOfRecipient > client.SmsAllowed)
    {
        return Request.CreateResponse<SmsData>(HttpStatusCode.NotAcceptable, smsData);
    }

    StoreSmsData ssd = new StoreSmsData();
    ssd.ClientId = smsData.ClientId;
    ssd.NoOfRecipient = smsData.NoOfRecipient;
    ssd = dbContext.StoreSmsData.Add(ssd);
    dbContext.SaveChanges();

    var response = Request.CreateResponse<StoreSmsData>(HttpStatusCode.Created, ssd);

    SentNumbers sn = new SentNumbers();
    foreach(Numbers num in smsData.Numbers){
        sn.ClientId = smsData.ClientId;
        sn.Msg = smsData.Msg;
        sn.SentDate = smsData.SentDate;
        sn.Numbers = num.Number;
        sn.NumbersId = num.Id;
        dbContext.SentNumbers.Add(sn);
        dbContext.SaveChanges();
    }

    response = Request.CreateResponse<SentNumbers>(HttpStatusCode.Created, sn);
    return response;
}

现在,当我访问服务器时,它会返回此响应消息:

{
    "Message":"An error has occurred.",
    "ExceptionMessage":"Object reference not set to an instance of an object.",
    "ExceptionType":"System.NullReferenceException",
    "StackTrace":"   at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   
    at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}

我无法理解这个问题。如何将数字存储在不同的表中。 当我使用断点调试时,Numbers和Msg值为null 。如何存储号码。在客户端,帖子很好......

1 个答案:

答案 0 :(得分:1)

我确实看到你的JSON格式错误。比如说,

工作代码

如果您有如下复杂模型

public class SmsData
{
    public int Id { get; set; }
    public IEnumerable<Numbers> SmsNumbers { get; set; }
}

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

然后您的行动采用以下方式 -

    public void Post(SmsData client)
    {
    }

然后你需要以下列方式进行JSON调用 -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>

    function SendSms() {
        var studentData = {
            "Id": 29,
            "SmsNumbers": [{ "Id": 98, "Number" : 123 }, { "Id": 90, "Number" : 130 }]
        };
        $.ajax({
            type: "POST",
            url: "http://localhost:23133/api/values",
            data: JSON.stringify(studentData),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            processData: true,
            success: function (data, status, jqXHR) {
                console.log(data);
                console.log(status);
                console.log(jqXHR);
                alert("success..." + data);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });
    }
</script>
<input type="submit" onclick="SendSms()" value="Click" />

观察子节点数据格式 -

    var studentData = {
        "Id": 29,
        "SmsNumbers": [{ "Id": 98, "Number" : 123 }, { "Id": 90, "Number" : 130 }]
    };

类似地,您需要在JSON中格式化嵌套类格式。 当我调试时,我得到了所有的值 -

enter image description here