我当前的行从文本框中请求产品编号:
string[] productNumbers = HttpContext.Current.Request.Form.GetValues("ProductNumber");
我尝试对其进行调整以获取 Qty 的值:
int[] qty = HttpContext.Current.Request.Form.GetValues("quantity_input");
但是我收到一个错误,无法将字符串转换为 int。那么我该如何使用这个 go 来获取 Int 呢?我只是想捕获它。
"CS0029: Cannot implicitly convert type 'string[]' to '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;
}
最佳答案
那么您必须将字符串值转换为整数,例如
List<int> qty = new List<int>();
foreach (string item in HttpContext.Current.Request.Form.GetValues("quantity_input"))
{
qty.Add(int.Parse(item));
}
如果您想防范非数字值,请使用 TryParse
。
关于c# - 如何使用 HttpContext 获取 int 值而不是 string 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22813994/