How to perform mathematical operation within the MVC view

Asked

Viewed 134 times

2

I am creating a web application MVC 5 for studies and I have a question: it is possible to perform a mathematical operation in view?

I wanted to multiply line 16. What would be the solution?

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.users.first_name_user) @Html.DisplayFor(modelItem => item.users.last_name_user)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.product.name_product)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.quantity)
    </td>
    <td>
        R$ @Html.DisplayFor(modelItem => item.product.price)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.quantity) * @Html.DisplayFor(modelItem => item.product.price) ******Preciso Realizar essa multiplicação****
    </td>
    <td>
        @Html.ActionLink("Editar", "Edit", new { id = item.id_order }) |
        @Html.ActionLink("Detalhes", "Details", new { id = item.id_order }) |
        @Html.ActionLink("Excluir", "Delete", new { id = item.id_order })
    </td>
</tr>
}

Tabela com resultados

I tried to use the code that way:

R$ @Html.DisplayFor(modelItem => item.quantity * item.product.price) 

Made that mistake:

Imagem do Erro

  • Why don’t you ride the model already with this calculated field. It is until the most certain to do.

  • Um, I hadn’t thought about the model. It came automatically mounted from a sql server database. I changing the model, it causes some impact on my database?

  • No, it’s all right.

  • You are using ORM ???

  • As a matter of fact, a week ago I started working on Asp. So I don’t know about ORM, but I will research about.

1 answer

3


The ideal is not to do processing in view, then the correct solution is to create the model that already includes the calculated total value as a field of the model (may be a viewmodel if you do not want to do in the normal model), and there you can easily use.

If you want the shape incorrect, but it works, you can do the account before and then use the result, something like this:

@{
foreach (var item in Model) {
    var total = item.quantity * item.product.price;
    ...
    @Html.DisplayFor(modelItem => total)
}

I put in the Github for future reference.

  • I added in the model the calculation that solved the problem public decimal total { get { Return Quantity * product.price; } } , and in the view I called the total

Browser other questions tagged

You are not signed in. Login or sign up in order to post.