【问题标题】:Pass an array from jQuery POST to C# WebApi将数组从 jQuery POST 传递到 C# WebApi
【发布时间】:2016-02-05 20:22:36
【问题描述】:

我正在尝试将数组从 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。任何想法我做错了什么?

【问题讨论】:

  • 这里有错误?哪个错误?
  • 尝试将data: { purchases } 更改为data: purchases。你将一个对象包装成一个对象。为什么?
  • @KaushikMaheta; “对象引用未设置为对象的实例”。
  • @YeldarKurmangaliyev:我仍然收到同样的错误“对象引用未设置为对象的实例”

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


【解决方案1】:
$(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"
        });
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2016-10-06
    • 2013-01-28
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多