ASP.NET MVC计算运费总计

如何用razor html计算运费总额。 第一件商品的运费为3.99美元,每件商品的运费为0.99美元。

@{ double itemTotal = 0; double subTotal = 0; int totalQty = 0; double discount = 0.8; double shippingBase = 3.99; double shippingItem = 0.99; } @foreach (var item in Model) { double price = (double)item.price / 100 * discount; itemTotal = @item.qty * price; subTotal += itemTotal; totalQty += @item.qty; 

使用此声明

第一件商品的运费为3.99美元,每件商品的运费为0.99美元。

提取以下数据以创建运费模型。

 public class ShippingCharge { public decimal basePrice { get; set; } public int baseCount { get; set; } public decimal unitPrice { get; set; } } 

使用OP中的示例将填充为

 //Shipping charges are shippingCharge = new ShippingCharge() { // $3.99 basePrice = 3.99M, //for the first item baseCount = 1, // $.99 for each additional item. unitPrice = 0.99M }; 

完成后,在给定项目计数的情况下,使用以下算法计算运费。

 decimal? CalculateShippingTotal(int itemCount, ShippingCharge charge) { decimal? total = null; if (charge != null) { var basePrice = charge.basePrice; var baseCount = charge.baseCount; if (itemCount > baseCount) { var qtyDifference = itemCount - baseCount; var additionalCost = qtyDifference * charge.unitPrice; total = basePrice + additionalCost; } else { total = itemCount * basePrice; } } return total; } 

以下unit testingvalidation算法在计算总运费方面的正确性。

 [TestMethod] public void _TotalShipping_For_One_Item() { //Arrange var totalQty = 1; var expected = 3.99M; //Act var actual = CalculateShippingTotal(totalQty, shippingCharge); //Assert actual.ShouldBeEquivalentTo(expected); } [TestMethod] public void _TotalShipping_For_Two_Items() { //Arrange var totalQty = 2; var expected = 4.98M; //Act var actual = CalculateShippingTotal(totalQty, shippingCharge); //Assert actual.ShouldBeEquivalentTo(expected); } [TestMethod] public void _TotalShipping_For_Three_Items() { //Arrange var totalQty = 3; var expected = 5.97M; //Act var actual = CalculateShippingTotal(totalQty, shippingCharge); //Assert actual.ShouldBeEquivalentTo(expected); } 

此答案目标具体如何根据OP计算运费,而不是折扣小计。 这应该足够简单,您可以通过统计项目,数量和价格来计算。 完成后,使用项目计数和费用来计算运费。

您可以在循环中添加简单条件和添加:

 @{ double itemTotal = 0; double subTotal = 0; int totalQty = 0; double discount = 0.8; double shippingBase = 3.99; double shippingItem = 0.99; double totalShipping = 0; //used to calculate the cumulative shipping total } @foreach (var item in Model) { double price = (double)item.price / 100 * discount; itemTotal = @item.qty * price; subTotal += itemTotal; totalQty += @item.qty; totalShipping += ((totalShipping >= shippingBase) ? shippingItem : shippingBase); }