0

The ASP statement looks like this:

adjmargin = Math.round(((mysell - mycost) / mycost)*100)

In the Razor View I am looping through multiple fields and I need to apply the above operation to a couple of them. So for instance I have some fields like this:

<td>
        @Html.DisplayFor(x => x.Cost)
        @Html.HiddenFor(x => x.Cost)
</td>
<td>
        @Html.DisplayFor(x => x.Sell)
        @Html.HiddenFor(x => x.Sell)
</td>

I'm assuming I'm going to have to assign the data from DisplayFor or HiddenFor to a variable and utilize those vars in a math function but I can't quite figure out what approach to take.

Rafe
  • 7,036
  • 5
  • 24
  • 27
  • You should move that to your model or controller. – SLaks Dec 27 '18 at 18:49
  • How `adjmargin` is used in the original ASP code? What's wrong with simple `@Html.DisplayFor(x => Math.round(((x.Sell - x.Cost) / x.Cost)*100))`? – SergGr Dec 27 '18 at 19:21
  • That would work except that the values from the DB were stored as string and double? instead of just double. The string I can use Convert.ToDouble on but the other one complains that it can't convert double to double?. – Rafe Dec 27 '18 at 19:30
  • OK, this compiles: @Html.DisplayFor(x => Math.Round(((Convert.ToDouble(x.Sell) - Convert.ToDouble(x.Cost)) / Convert.ToDouble(x.Cost)) * 100)) but I'm getting an error stating "Templates can be used only with field access, property access, single-dimension array index, or single parameter custom indexer expressions". – Rafe Dec 27 '18 at 19:39
  • 1
    Why don't you just make a view model that does this logic for you? Then just display the properties from the view model without any logic needed in the razor page. – A. Hasemeyer Dec 27 '18 at 19:56
  • Sounds like a great idea, but I wouldn't know where to begin. I'm new to this. – Rafe Dec 27 '18 at 19:59
  • Figured it out: @(Math.Round(Convert.ToDouble(Model.Sell) - Convert.ToDouble(Model.Cost) / Convert.ToDouble(Model.Cost),2) * 100) – Rafe Dec 27 '18 at 21:56
  • Side note: @Rafe are you using "ASP" as synonym of C#/ASP.Net or actually true [ASP classic](https://en.wikipedia.org/wiki/Active_Server_Pages) from 1996? Please avoid calling C# code "ASP" or "ASP.Net" if former.. (consider [edit] title at least) – Alexei Levenkov Dec 28 '18 at 05:32
  • Updated question to reflect that this is indeed ASP Classic. – Rafe Dec 28 '18 at 16:43

1 Answers1

0

This worked:

@(Math.Round(Convert.ToDouble(Model.Sell) - Convert.ToDouble(Model.Cost) / Convert.ToDouble(Model.Cost),2) * 100)
Rafe
  • 7,036
  • 5
  • 24
  • 27
  • It generally considered bad idea to put a lot (or even any) of logic into a view. Better solution would be to move calculation to controller and pass through view model - https://stackoverflow.com/questions/45708470/how-to-display-a-calculated-value-in-a-view – Alexei Levenkov Dec 28 '18 at 05:29
  • Thanks Alexei, I'll try refactoring this to something more in line with best practices. – Rafe Dec 28 '18 at 16:42