somango
somango

Reputation: 31

Calculation Not Displaying Correctly In Razor

I am new to asp.net MVC and have a question on the Razor View.

I'm having some issues display the result of a calculation

I have the following code:

 foreach (var item in Model.Items)
        {
            <tr class="ourProduct">
                <td>
                    <div class="ourProductDesc">
                        <h4>
                            @item.Description
                        </h4>

                        <div class="ourPrice">
                            <span>£ @item.price</span>
                        </div>
                    </div>
                </td>

                <td class="ourPrice">
                    £ @item.Quantity * item.price
                </td>
            </tr>
        }

I would really appreciate if someone could tell me how to do this calculation and display the results as expected. Currently I am getting an incorrect output:

£ 1 * item.Prod.price

Upvotes: 2

Views: 953

Answers (2)

Harko
Harko

Reputation: 413

You're almost there - you just have to wrap the calculation inside ( )

Also when writing HTML instead of writng £ you should use "&pound" - There are lots of special characters and codes - Here's a useful site for a list of characters and codes: http://character-code.com/

Back to your orginal question:

Update your code to the following and it should work as expected:

foreach (var item in Model.Items)
        {
            <tr class="ourProduct">
                <td>
                    <div class="ourProductDesc">
                        <h4>
                            @item.Description
                        </h4>

                        <div class="ourPrice">
                            <span>&pound; @item.price</span>
                        </div>
                    </div>
                </td>

                <td class="ourPrice">
                    &pound; @(item.Quantity * item.price)
                </td>
            </tr>
        }

Upvotes: 6

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Enclose the razor code calculation part inside @() as shown :-

@foreach (var item in Model.Items)
    {
        <tr class="ourProduct">
            <td>
                <div class="ourProductDesc">
                    <h4>
                        @item.Description
                    </h4>

                    <div class="ourPrice">
                        <span>£ @item.price</span>
                    </div>
                </div>
            </td>

            <td class="ourPrice">
                £ @(item.Quantity * item.price) // correct here
            </td>
        </tr>
  }

and instead of £ you can use &pound.

Upvotes: 1

Related Questions