Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从HttpContext.request对象获取列表_C#_Jquery_Asp.net - Fatal编程技术网

C# 从HttpContext.request对象获取列表

C# 从HttpContext.request对象获取列表,c#,jquery,asp.net,C#,Jquery,Asp.net,我使用jQuery序列化了一个表单,并将其以以下格式发送到服务器: Object{ transactionID : "10779" itemList : [{itemName:"ball", quantity: 5}, {itemName:"stuff", quantity:10}] } 在自定义ASP.NET modelbinder中,我执行以下操作: HttpRequestBase request = controllerContext.HttpContext.Request;

我使用jQuery序列化了一个表单,并将其以以下格式发送到服务器:

Object{
transactionID : "10779"
itemList : [{itemName:"ball", quantity: 5}, {itemName:"stuff", quantity:10}]
}
在自定义ASP.NET modelbinder中,我执行以下操作:

HttpRequestBase request = controllerContext.HttpContext.Request;
        List<Item> itemList = new List<Item>();

        foreach (var item in request.Form.Get("itemList"))
        {
            itemList.Add(new TransactionItemQuantity
            {
               name = item.itemName               
               quantity = item.quantity
            });
        }

        return new Transaction
        {
             transactionID = request.Form.Get("transactionTypeID"),
             itemList = itemList
        };
    }
HttpRequestBase request=controllerContext.HttpContext.request;
List itemList=新列表();
foreach(request.Form.Get(“itemList”)中的var项)
{
itemList.Add(新事务项数量)
{
name=item.itemName
数量=项目数量
});
}
返回新事务
{
transactionID=request.Form.Get(“transactionTypeID”),
itemList=itemList
};
}

但是,foreach循环不起作用,因为IDE还不知道request.Form.Get(“itemList”)返回一个对象数组。如何使上述代码正常工作?

如果这样做,则只能从请求返回一个字符数组。您需要将
request.Form.Get(“itemList”)
的内容反序列化到您的项目列表中,然后您可以遍历它们。 大概是这样的:

var list = JsonConvert.DeserializeObject<List<Item>>(request.Form.Get("itemList"));
var list=JsonConvert.DeserializeObject(request.Form.Get(“itemList”);
您还将首先创建类型为
Item
的列表,但尝试在循环中添加类型为
TransactionItemQuantity
的对象


编辑:添加示例

您是否首先在某个位置反序列化JSON字符串?不,它按原样使用。