[英]Get a list from an HttpContext.request object
Using jQuery I have serialized a form that and send it to the server in this format: 我使用jQuery序列化了一个表单,并以这种格式将其发送到服务器:
Object{
transactionID : "10779"
itemList : [{itemName:"ball", quantity: 5}, {itemName:"stuff", quantity:10}]
}
In a custom ASP.NET modelbinder, I do this: 在自定义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
};
}
However, the foreach loop does not work, as the IDE doesn't yet know that request.Form.Get("itemList") returns an array of objects. 但是,由于IDE尚不知道request.Form.Get(“ itemList”)返回对象数组,因此foreach循环不起作用。 How do I make the above code work? 如何使以上代码起作用?
If you do it like this you only get a char-array back from the request. 如果这样做,您只会从请求中获得一个char数组。 You need to deserialize the content of request.Form.Get("itemList")
into a List of your items, then you can loop through them. 您需要将request.Form.Get("itemList")
的内容反序列化为项目列表,然后可以遍历它们。 Something like this: 像这样:
var list = JsonConvert.DeserializeObject<List<Item>>(request.Form.Get("itemList"));
You are also creating a list of type Item
first, but trying to add objects of type TransactionItemQuantity
in the loop. 您还将首先创建Item
类型的列表,但尝试在循环中添加TransactionItemQuantity
类型的对象。
Edit: Added example 编辑:添加示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.