Reputation: 81
im quite new to MVC and am finding it hard to find resources on stuff like this
I have a model:
public class Distance
{
public int Id { get; set; }
[DisplayName("Distance Run")]
public float DistanceRun { get; set; }
[DisplayName("Chose a date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime _Date { get; set; }
[DisplayName("Any Addtional Comments")]
public String AdditionalComments { get; set; }
}
I would like to display on my view of this model all total Distance run, in the top corner. Would it be best to use the whole:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.DistanceRun)Km
</td>
<td>
@Html.DisplayFor(modelItem => item._Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.AdditionalComments)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
Foreach loop to calculate it by adding each Distance KM or would it make sense to create a near to identical view with its own separate action in a controller to calculate distance?
Upvotes: 0
Views: 163
Reputation: 15934
As noted from the comments, you've actually got a collection of Distance
as the model for the view. I propose you create a new ViewModel for this view such as:
public class DistancesViewModel
{
public ICollection<Distance> Distances { get; set; }
public int TotalDistanceRun {
get {
return Distances.Sum(d => d.DistanceRun)
}
}
}
Then bind your View to that ViewModel instead. You can then access @Model.TotalDistanceRun
and still use the Distances in a loop etc via Model.Distances
.
The advantage for me in this approach is avoiding code on the view as you may need to change how the total distance is calculated at some point and doing it on the ViewModel is cleaner.
Upvotes: 1
Reputation: 218847
From the code in the view, it looks like the view model is actually a collection of that particular model. Something like:
@model IEnumerable<Distance>
(or anything similar, it makes little difference for this)
If that's the case then your view already has the data it needs, you just need to bind to it. A calculated value doesn't need any kind of two-way binding, so you can just output it to the page wherever you like. Something as simple as this:
Total Distance: @Model.Sum(d => d.DistanceRun)
You can include any formatting you like, perhaps by appending a .ToString()
with a custom format. But binding to the model in this case is as simple as just outputting the value like that.
Upvotes: 2