ASP.NET MVC > Views - Razor Engine

Mathematical operation in Razor view in ASP.NET MVC

How to perform mathematical operation in the razor view?

If the declared variable is of number type, we can simply use the mathematical operators like +, -, * or / etc. prefixed with @ and wrapped with "(" and ")". 

<p>Sum is @(a + b)</p> 
<p>Multiplication is @(a * b)</p>

If the variable is of string type, we need to convert them into respective number type and use the mathematical operators. 

The value of a is @(sum.AsInt() + 6)


AsInt() converts the sum variable that is of string type to Integer and adding 6 into it. Similar to .AsInt() we have .AsDecimal() etc. functions.

Instead of .AsInt(), we could have also used C# int.Parse() to convert the string into integer.

The value of a is @(int.Parse(sum) * 50) 

In the above code, assuming that sum variable of string type, gets converted into integer and multiplied with 50 and the result is rendered.

 Views: 7381 | Post Order: 16

Write for us