我有一个从文本框中请求产品#的当前行:
string[] productNumbers = HttpContext.Current.Request.Form.GetValues("ProductNumber");
我试图调整它以获得Qty的值:
int[] qty = HttpContext.Current.Request.Form.GetValues("quantity_input");
但是我收到一个错误,它无法将字符串转换为int。那我怎么用这个去获得一个Int?我只想抓住它。
“CS0029:无法将类型'string []'隐式转换为'int'”
我的完整代码是:
CartItemCollection items = new CartItemCollection();
Cart cart = Core.GetCartObject();
string skus = "";
string debugStr = "";
Product product = null;
int[] qty = HttpContext.Current.Request.Form.GetValues("quantity_input");
try
{
string[] productNumbers = HttpContext.Current.Request.Form.GetValues("ProductNumber");
foreach (string productNumber in productNumbers)
{
debugStr = debugStr + "-p=" + productNumber;
if(!string.IsNullOrEmpty(productNumber.Trim()) && !productNumber.StartsWith("Enter Product #"))
{
try
{ //redirect if no product found
product = Core.GetProductObjectByProductNumber(productNumber);
}
catch (Exception e)
{
debugStr = debugStr + "-e=noproductfound";
continue; //do nothing, process the next user input
}
//check if we have a valid product object, allow virtual and other type(s) for adding directly to cart which may need special handling
if(product != null)
{
debugStr = debugStr + "-t=" + product.ProductTypeName;
if(!product.ProductTypeName.Equals("NORMAL"))
{
//assume VIRTUAL (or other type) and redirect for selecting child/group products or other special handling
form.Redirect("product.aspx?p=" + product.ProductNumber);
}
else
{
debugStr = debugStr + "-a=noattributesadd";
CartItem item = new CartItem(context);
item.ProductId = product.ProductId;
item.Quantity = qty;
items.Add(item);
}
skus = skus + ";" + productNumber;
product = null; //reset the product object in case the next product number submitted is invalid
} //product not null
} //sanity check for empty or default data
} //iterate on each product submitted
cart.AddItems(items);
form.Redirect("cart.aspx?skus=" + skus);
}
catch (Exception e)
{
form.AddError("*** ProductNumber provided was not found ***");
form.Redirect("quickorder.aspx?qo=2&e=" + e.Message);
return;
}
答案 0 :(得分:2)
嗯,你必须将字符串值转换为整数,例如
List<int> qty = new List<int>();
foreach (string item in HttpContext.Current.Request.Form.GetValues("quantity_input"))
{
qty.Add(int.Parse(item));
}
如果您想防止非数字值,请使用TryParse
。
答案 1 :(得分:0)
它将始终返回一个字符串[],您可以使用以下Linq语句将字符串[]转换为int []。
string[] result = HttpContext.Current.Request.Form.GetValues("quantity_input");
int[] quantityInputs = result.Select(x => int.Parse(x)).ToArray();