将一个数组从jQuery POST传递到C#WebApi

本文关键字:POST jQuery C#WebApi 数组 一个 | 更新日期: 2023-09-27 18:20:34

我试图将一个数组从jQuery POST传递到C#WebApi服务,但我得到了以下错误:

对象引用未设置为对象的实例。

jQuery代码:

 $(document).ready(function ()
    {
        $("#btn").click(function ()
        {
          var purchases = { dealid1: ["2", "3", "4"], theatid1: "5", mouvid1: "408", bookdt1: "10/11/2015", shtime1: "11:00AM", fbid1: "100" };
           $.ajax(
            {
                type: "POST",
                data: { purchases },
                url: "api/purchase",
                contentType: "application/json"
            });
        });
    });
<input type="button" value="mybtn" id="btn" />

WebApi代码:

 public object post([FromBody] purchase purchases)
    {
        return Request.CreateResponse(jsonvalues(purchases));
    }
    private object jsonvalues(purchase purchases)
    {
        object result = false;
        for (int i = 0; i < purchases.dealid1.Length; i++)//I got error here//
        {
           int count= purchases.dealid1.Count();
            dealid = purchases.dealid1;
            string arr = dealid[i];
        }
            theatid = purchases.theatid1;
            mouvid = purchases.mouvid1;
            bookdt = purchases.bookdt1;
            shtime = purchases.shtime1;
            fbid = purchases.fbid1;
    }
 public class purchase
{
    public string[] dealid1 { get; set; }
    public string theatid1 { get; set; }
    public string mouvid1 { get; set; }
    public string bookdt1 { get; set; }
    public string shtime1 { get; set; }
    public string fbid1 { get; set; }
}

我可以获得其他值,如theatid1mouvid1等。但dealid1不可访问。你知道我做错了什么吗?

将一个数组从jQuery POST传递到C#WebApi

$(document).ready(function ()
{
    $("#btn").click(function ()
    {
      var purchases = { dealid1: ["2", "3", "4"], theatid1: "5", mouvid1: "408", bookdt1: "10/11/2015", shtime1: "11:00AM", fbid1: "100" };
       $.ajax(
        {
            type: "POST",
            data: JSON.stringify( purchases ),
            url: "api/purchase",
            contentType: "application/json"
        });
    });
});