asp.net-mvc asp.net mvc razor 将两项相乘并转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4386830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:37:22  来源:igfitidea点击:

asp.net mvc razor multiply two item and convert to string

asp.net-mvcrazor

提问by Bar??

When I write @(line.Quantity * line.Product.Price).ToString("c")the result is

当我写 @(line.Quantity * line.Product.Price).ToString("c")结果是

39,00.ToString("c") 

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

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

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

How can i multiply two values and convert it to string in a razor view?

如何在剃刀视图中将两个值相乘并将其转换为字符串?

回答by jgauffin

try

尝试

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

The problem is that razor do not know when the output string ends since @ is used to display code in HTML. Spaces switches razor back to HTML mode.

问题是 razor 不知道输出字符串何时结束,因为 @ 用于在 HTML 中显示代码。Spaces 将剃刀切换回 HTML 模式。

Wrapping everything into parenthesis makes razor evaluate the entire code block.

将所有内容都括在括号中使 razor 评估整个代码块。

Although the most proper way would be to introduce a new property in your model:

虽然最正确的方法是在模型中引入一个新属性:

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

and simply use:

并简单地使用:

@line.Total.ToString("c")