Asp.net-Mvc

asp.net mvc razor 將兩項相乘並轉換為字元串

  • June 29, 2021

當我寫 @(line.Quantity * line.Product.Price).ToString("c")結果是

39,00.ToString("c") 

結果@line.Quantity * line.Product.Price.ToString("c")

2 * line.Product.Price.ToString("c") 

如何將兩個值相乘並將其轉換為剃刀視圖中的字元串?

嘗試

@((line.Quantity * line.Product.Price).ToString("c"))

問題是 razor 不知道輸出字元串何時結束,因為 @ 用於在 HTML 中顯示程式碼。Spaces 將剃刀切換回 HTML 模式。

將所有內容包裝到括號中會使 razor 評估整個程式碼塊。

儘管最合適的方法是在模型中引入新屬性:

public class MyModel
{
  public double Total { get { return Quantity * Product.Price; }}
  //all other code here
}

並簡單地使用:

@line.Total.ToString("c")

引用自:https://stackoverflow.com/questions/4386830