MVC 4 Views and Razor code (and showing an aggregation from an entity)

This is an example situation where Razor can be useful to allow code on a view: in this case, I have a view model like this one (very simplified):

public class Product
{
public Guid ProductId {get;set;}
public string Description {get;set;}

public virtual List ProductTransactions {get;set;}

}

public class ProductTransaction
{
public Guid TransactionId {get;set;}
public decimal Amount {get;set;}

public Guid ProductId {get;set;}
[ForeignKey("ProductId")]
public virtual Product Product {get;set;}

}

then, if I want to see a list of products with total amounts, in my view, I could use something like this:

<table>
  <thead>
    <tr>
      <td>
          @Html.LabelFor(x => x.Product[0].Description)
      </td>
      <td>
           @Html.LabelFor(x => x.Product[0].ProductTransactions[0].Amount)
      </td>
     </tr>
   </thead>
   <tbody>
    @foreach (var product in Model.Product) 
      {
       <tr>
         <td>
             @Html.DisplayFor(x => product.Description)
         </td>
        <td>
           @{ decimal totalAmount=0;
           foreach (var transaction in Product.ProductTransactions)
              {
                totalAmount= totalAmount+ transaction.Amount;
               }
            @Html.DisplayFor(x => totalAmount)
            }
       </td>
      </tr>
      }
    </tbody>
</table>

Of course this is not the complete code of the View, I just focused on what’s relevant to the use of code inside the view using Razor, for a specific purpose, in this case, obtain aggregation of the Amount for each one of the products in the corresponding entity (at the DB).

Cheers.

2 thoughts on “MVC 4 Views and Razor code (and showing an aggregation from an entity)

  1. If the total is used in more than one view, i.e. the total amount is something you use in different places (maybe not only views), you could also do what you just did by adding a property to the Product model – like this:

    public class Product
    {
    public Guid ProductId { get; set; }
    public string Description { get; set; }

    public decimal TotalAmount {
    get { return ProductTransactions.Sum(x => x.Amount); }
    }

    public virtual List ProductTransactions { get; set; }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *