Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I write @(line.Quantity * 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?

like image 958
Barış Avatar asked Dec 08 '10 11:12

Barış


People also ask

What is the purpose of the AsInt () function in MVC Razor?

AsInt(String)Converts a string to an integer.

How do you write a multi statement code block in Razor?

Multi-statement Code blockYou can write multiple lines of server-side code enclosed in braces @{ ... } . Each line must ends with a semicolon the same as C#.

Does ASP.NET MVC use Razor?

Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.

What is @: In Cshtml?

This operator is useful in conjunction with other Razor server side operators when you want to output something as a literal text. For example: @if (model. Foo) { @:Some text to be written directly. }


1 Answers

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")
like image 90
jgauffin Avatar answered Oct 04 '22 20:10

jgauffin