This is the model I pass to my view as list:
public class DogContentPage : ContentPage
{
public string Name { get; set; }
public string Age { get; set; }
public bool IsFemale { get; set; }
public string Image { get; set; }
public List<string> Merits { get; set; }
}
View:
@model List<EmmysBlog_Core.Models.Dog.DogContentPage>
As you can see the model contains a list of strings (Merits). I have troubles looping through the list of Merits. Im suspecting that the reasin for this is that i pass the model as a list..Is it possible for me to loop through merits?
This attempt:
@foreach (var item in Model)
{
<li>@item.Merits</li>
}
Only gives me a list of: System.Collection.Generic...
Do I have to change the way I pass the model to the view or is there another way of constructing the loop in order to access the values in Merits?
View:
@foreach (var dogs in Model.Where(o => o.IsFemale))
{
<div class="media">
<div class="col-md-4">
<a href="#">
<img src="@dogs.Image" style="width: 100%">
</a>
</div>
<div class="col-md-4" style="text-align: center;">
<a href="#"><h3 class="media-heading">@dogs.Name</h3></a>
@Html.ActionLink("Stamtavla", "Dog", "Home", new { pageId = dogs.Id }, null)
</div>
<div class="col-md-4">
<ul>
@foreach (var item in Model)
{
foreach (var merit in item.Merits)
{
<li>@merit</li>
}
}
</ul>
</div>
</div>
}
</div>
</div>
An iterator can be used to step through collections such as lists and arrays. An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time.
A for loop is very valuable when we need to iterate over a list of elements or a range of numbers. Loop can be used to iterate over a list, data frame, vector, matrix or any other object. The braces and square bracket are compulsory.
C# foreach loop is used to iterate through items in collections (Lists, Arrays etc.). When you have a list of items, instead of using a for loop and iterate over the list using its index, you can directly access each element in the list using a foreach loop.
Just add another foreach
for the Merits
list
@foreach (var item in Model)
foreach (var merit in item.Merits)
{
<li>@merit</li>
}
Update
Then just strip off the outer loop:
foreach (var merit in dogs.Merits)
{
<li>@merit</li>
}
You would need to do something like this:
@foreach (var item in Model)
{
<ul>
@foreach(var merit in item.Merits)
{
<li>@merit</li>
}
</ul>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With