Natasha Thapa
Natasha Thapa

Reputation: 969

Add Values in model in View

I am very new to MVC 3 Razor in ASp.net. i am sending a model to a view that is tightly coupled to this model. this model has list and i want to display a SUM of particular field in that model list. is that possible and how?

Upvotes: 1

Views: 5043

Answers (3)

Natasha Thapa
Natasha Thapa

Reputation: 969

Decimal D = listItem.Where(P=>P.Amount>100).Sum(P=>P.Amount);

Upvotes: 0

RPM1984
RPM1984

Reputation: 73112

I wouldn't do it in the View.

I'd do it in the ViewModel:

public class SomeViewModel
{
   public ICollection<int> SomeValues { get; set; }
   public int MySum { get { return SomeValues.Sum(x => x.SomeValue); } }
}

Then the view:

@Html.DisplayFor(model => model.MySum)

Alternatively you could use a generic HTML helper, made generic so you can re-use across any model which has an IEnumerable<T> that can be aggregated.

Always try and keep your View clear of unnecessary logic.

Upvotes: 5

aligray
aligray

Reputation: 2832

This should do it, but without seeing some of your code it's hard to be exact:

@Model.YourList.Sum(p => p.PropertyNameYouWantToSum)

Upvotes: 3

Related Questions