C# 从HttpContext.request对象获取列表
我使用jQuery序列化了一个表单,并将其以以下格式发送到服务器: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;
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字符串?不,它按原样使用。