简体   繁体   中英

Getting post array in Asp.net MVC

I am writing a web api2 program that handles sms-contacts. There is a JSON post to the server like this:

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

and in Server I have a class to handle this JSON as below:

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; }
}

and Controller is:

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;
}

Now when I access the server it returns this Response Message:

{
    "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()"
}

I cannot understand the problem. How can i store the numbers in a different table. Also when I debugged with break point the Numbers and Msg value is null . How can I Store the number.In Client Side the Post is fine...

I do see your JSON formatting is wrong. Say for example,

WORKING CODE

If you have complex model as follows

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; }
}

Then your Action is in the following way -

    public void Post(SmsData client)
    {
    }

Then you need to make a JSON call in the following way -

<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" />

Observe the child nodes data format -

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

Similarly you need to format the nested classes format in JSON. When I debug I got all the values -

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM