开发者

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

When I write @(line.Quant开发者_开发问答ity * line.Product.Price).ToString("c") the result is

39,00.ToString("c") 

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

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

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


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.

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

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")


this is an old question but I have just had the same issue and here is the resolution for it.

If you need to perform a calculation on a razor view, you can do it the following way:

if you are outside of c# block (such as @foreach or @if ): you can wrap your calculation into @{ } and they won't be rendered.

<p>Some text</p>
@{ var x = Model.Y * Model.Z; }
<p>X equals @x.ToString()</p>

if you are inside of a c# block: you can simply put your calculations in { }.

<p>Some text</p>
@foreach (var x in Model.Y)
{
    { var z = x * 2; }
    <p>Z equals @z.ToString()</p>
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜