1

RazorEngine is used to run C# Razor views in ASP.NET MVC4 application.

Views contain decimal expressions wrapped to custom Format function call like

<div>@Format(somedecimalexpression/someotherdecimalexpression)</div>

This causes exception

Attempted to divide by zero

if someotherdecimalexpression value is 0

How to force razor engine to ignore division by zero exception? It can return big decimal number or null on empty string if this occurs.

Expressions are created by end users at runtime. Database fields have decimal type and it is difficult to convert all operands to double to remove this exception.

Check for artihmetic overflow is unchecked in project properties but this does not help. I tried

<div>@Eval("somedecimalexpression/0")</div>

and in template base class

public string Eval(string expression) {

try {

  return Format(Run(expression));
}
catch (DivideByZeroException) {
  return ""
}

}

but got compile error since there is not Run method.

Andrus
  • 26,339
  • 60
  • 204
  • 378
  • 1
    You should avoid placing any logic into views. So you might add another readonly property to you model which will display division in format you need – Uriil May 24 '14 at 08:42

2 Answers2

1

I agree with Uriil's comment. If you still want the logic on the view you can get around the error using an if

<div>
    @if(someotherdecimalexpression != 0){
        Format(somedecimalexpression/someotherdecimalexpression)
    }
</div>
Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
  • expression can be sophisticated, can contain number of divisions, calls to .NET methods and other artimethics operations. How to find all someotherdecimalexpresioon expressions which can cause division errors ? It looks like your answer required manually parsing expressions to find possible divisions by zero. How to implement this ? – Andrus May 24 '14 at 16:51
1

If you know the name of someotherdecimalexpression at runtime you could do the following:

string name = "someotherdecimalexpression";
template = template.Replace(name, "(double)" + name);

This will convert all someotherdecimalexpression to double for the calculation and you get Infinity instead of an exception.

But be aware of the "side effects" like if the name is something which could also be used e.g. "in text"...

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113