Reputation: 6083
How can I sum values at MVC view? I want to sum all KwotaOplaty records that are now displayed. Notice that i'm using SEARCHING (at controller) so when i search specific records i want to sum them all.
Controller:
public ActionResult Index(string oplataTyp, string szukajRej)
{
var TypLista = new List<RodzajOplaty>();
var TypWyszukaj = from d in db.Oplaty orderby d.RodzajOplaty select d.RodzajOplaty;
TypLista.AddRange(TypWyszukaj.Distinct());
ViewBag.oplataTyp = new SelectList(TypLista);
var oplaty = from p in db.Oplaty select p;
RodzajOplaty RodzajOplaty;
if (Enum.TryParse<RodzajOplaty>(oplataTyp, out RodzajOplaty))
{
oplaty = oplaty.Where(x => x.RodzajOplaty == RodzajOplaty);
}
if (!String.IsNullOrEmpty(szukajRej))
{
oplaty = oplaty.Where(s => s.TablicaRejstracyjna.Contains(szukajRej));
}
return View(oplaty.ToList());
}
View:
@model IEnumerable<AutoMonit.Models.Oplata>
<h2>Zestawienie opłat pojazdów</h2>
<p>
@Html.ActionLink("Utwórz", "Create")
</p>
@*@using (Html.BeginForm())
{
<div>Numer rejestracyjny: </div>
<div>@Html.TextBox("NumerRej")</div>
<input type="submit" value="Szukaj" />
}*@
@using (Html.BeginForm("Index", "Oplatas", FormMethod.Get))
{
<p>
Rodzaj oplaty: @Html.DropDownList("oplataTyp", "Wszystkie")<br />
Numer rejestracyjny: @Html.TextBox("szukajRej") <br />
<input type="submit" value="Szukaj" />
</p>
}
<br />
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.TablicaRejstracyjna)
</th>
<th>
@Html.DisplayNameFor(model => model.Pojazd.Marka)
</th>
<th>
@Html.DisplayNameFor(model => model.DataOplaty)
</th>
<th>
@Html.DisplayNameFor(model => model.PrzebiegOplaty)
</th>
<th>
@Html.DisplayNameFor(model => model.RodzajOplaty)
</th>
<th>
@Html.DisplayNameFor(model => model.KwotaOplaty)
</th>
<th>
@Html.DisplayNameFor(model => model.DodatkoweInformacjeOplaty)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TablicaRejstracyjna)
</td>
<td>
@Html.DisplayFor(modelItem => item.Pojazd.Marka)
</td>
<td>
@Html.DisplayFor(modelItem => item.DataOplaty)
</td>
<td>
@Html.DisplayFor(modelItem => item.PrzebiegOplaty)
</td>
<td>
@Html.DisplayFor(modelItem => item.RodzajOplaty)
</td>
<td>
@Html.DisplayFor(modelItem => item.KwotaOplaty)
</td>
<td>
@Html.DisplayFor(modelItem => item.DodatkoweInformacjeOplaty)
</td>
<td>
@Html.ActionLink("Edytuj", "Edit", new { id=item.ID }) |
@Html.ActionLink("Szczegóły", "Details", new { id=item.ID }) |
@Html.ActionLink("Usuń", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
<hr />
<h2>Suma kosztów:</h2>
@*Here i want to display sum*@
Upvotes: 1
Views: 21355
Reputation: 906
You should be able to that using Sum method and putting the result value in a ViewBag value and referencing it using Razor. It should be something like this:
In the Controller
ViewBag.Total = yourCollection.Sum(x => x.ThePropertyYouWantToSum);
In the View
@ViewBag.Total
Remember to include
using System.Linq;
Upvotes: 4