hamza rafiq
hamza rafiq

Reputation: 135

MVC 5 asp.net Inside Foreach Each Sum Related Data from other table

Models are ,

ModelA:

 public int AId       {get;set;}
 public float Amount {get;set;}

ModelB:
  public int   BId              {get;set;}
  public float RequestAmount    {get;set;}
  public int AId                {get;set;}
  public virtual ModelA ModelA  {get;set;}

now when i want to list the ModelA, there as many item in ModelB related ModelA i want to calculate RequestAmount and list in ModelA foreach list:

   public ActionResult Index()
    {
        var modelA = db.ModelA.Include(c => c.ModelB);
        return View(modelA.ToList());
    } 

this will be the view:

@model IEnumerable<test.Models.ModelA>


@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.AId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
        <td>
            **Here need to calcut or SUM value from ModelB only related to this**
        </td>
    </tr>

}

Upvotes: 1

Views: 1267

Answers (1)

Shyju
Shyju

Reputation: 218732

You can join both the collection and group the result and do a Sum, project the result to a new view model.

So create the view model first

public class MyViewModel
{
  public int AId { set;get;}
  public float Total { set;get;}
}

Now in your action method,

var data = (from a in db.ModelAs
            join b in db.ModelBs on a.AId equals b.AId
                group b by a.AId into g
    select new MyViewModel { AId = g.Key, Total = g.Select(f=>f.RequestAmount).Sum() })

.ToList(); 

And of course now your view is strongly typed to a list of MyViewModel

@model List<MyViewModel>
@foreach(var item in Model)
{
  <p>@item.AId</p>
  <p>@item.Total </p>
}

Another option is, you can add a collection of ModelB to the ModelA class.

public class ModelA
{
   public int AId       {get;set;}
   public float Amount {get;set;}
   public IEnumerable<ModelB> ModelBs {set;get;}
}

and use the Sum extension method.

@model IEnumerable<test.Models.ModelA>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.AId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
        <td>
            @item.ModelBs.Sum(x=>x.RequestAmount)
        </td>
    </tr>

}

Upvotes: 1

Related Questions