0

I have a view that is using a model. I just need to do a simple subtraction on the model variables using razor.

Here is what the code looks like:

    @model Inquiry.Inq_Weights


<table id="mainWeights">

        <tr>
            <td>@Html.DisplayFor(model => Model.HotScaleHalfId)</td>
            <td>@Html.DisplayFor(model => Model.HotScaleGrossWeight)</td>
            <td>@Html.DisplayFor(model => Model.HotScaleTareWeight)</td>
        </tr>
    <tr>
        <td><strong>Total Hot Scale Weight</strong></td>
    </tr>
    <tr>
    <td align="right">(@Model.HotScaleGrossWeight - @Model.HotScaleTareWeight;)</td>
    </tr>
</table>

I am trying the (@Model.HotScaleGrossWeight - @Model.HotScaleTareWeight;) but it is just displaying "0 - 0". The zeros are correct at this point. but i don't want it to display the expression, just the result of that operation. I have also tried using a variable then listing that, as in

        @{
        var netWeight = @Model.HotScaleGrossWeight - @Model.HotScaleTareWeight;
        netWeight;
    }

But that doesn't work either. How can I do simple math on model members?

rigamonk
  • 1,179
  • 2
  • 17
  • 45

1 Answers1

2

You should do this:

  @(Model.HotScaleGrossWeight - Model.HotScaleTareWeight)

With your other example:

@{
    var netWeight = Model.HotScaleGrossWeight - Model.HotScaleTareWeight;
 }

Then use it with @netWeight. Please note that the @ symbol is razor specific, you don't have prefix your variables with it inside a c# expression. When you write @ you are actually saying that you are going to write a c# expression. Writing @ before Model is just for the razor engine to know that this is going to be a c# expression (your variable actually) and not a simple text 'Model'.

But I recommend to do this kind of stuff within your controller.

update

as Alexei wrote in comment @ is not just for razor: What does the @ symbol before a variable name mean in C#?

Community
  • 1
  • 1
Peter Porfy
  • 8,921
  • 3
  • 31
  • 41