I need to display employee names and their corresponding image below on a blazor webpage, So far I have the names displayed fine but can only loop through one image due to not knowing how to loop through the wwwroot folder so each name has the same image.
<h1>Northwind Employees</h1>
@foreach (Employee employee in NorthWindEmployees)
{
<h3 style="text-align: center;">
@employee.FirstName @employee.LastName <br>
</h3>
<div width="100" height="100" style="vertical-align:middle; text-align:center">
<img src="/images/EmpID1.jpg" /> //the reason for each name having the same image
</div>
}
@code {
public List<Employee> NorthWindEmployees;
protected override void OnInitialized()
{
Northwind db = new Northwind();
NorthWindEmployees = db.Employees.ToList();
}
}
How do I loop through the \wwwroot\images\ folder to display each employee image with their name?
How do I loop through the \wwwroot\images\ folder to display each employee image with their name?
Let's say, you have Image folder within your wwwroot. In this scenario, you would need to access that image as following:
As you can see, I have ImageNameFolder inside wwwroot so you would access it as following:
<img src="ImageFolder/ImageName"
class="rounded-square"
height="50" width="75"
style="border:1px"
accept="image/*" />
When you would have List:
Let's assume your NorthWindEmployees model looks as like below:
public class NorthWindEmployees
{
public string? EmployeeName { get; set; }
public string? ImageName { get; set; }
}
Therefore, you would access it as following:
@foreach (Employee employee in NorthWindEmployees)
{
<h3 style="text-align: center;">
@employee.EmployeeName <br>
</h3>
<div width="100" height="100" style="vertical-align:middle; text-align:center">
<img src="Image/@employee.ImageName"
class="rounded-square"
height="50" width="75"
style="border:1px"
accept="image/*" />
</div>
}
Note: You can use styte either in your src or in div as well.
Complete Demo:
<table>
<thead>
<tr>
<th>
Employee Name
</th>
<th>
Employee Picture
</th>
</tr>
</thead>
<tbody>
@foreach (var employees in NorWindsEmployeeList)
{
<tr>
<td>
@employees.EmployeeName
</td>
<td>
<img src="Image/@employees.ImageName"
class="rounded-square"
height="50" width="75"
style="border:1px"
accept="image/*" />
</td>
</tr>
}
</tbody>
</table>
@code {
public class NorWindsEmployees
{
public string EmployeeName { get; set; }
public string ImageName { get; set; }
}
List<NorWindsEmployees> NorWindsEmployeeList = new List<NorWindsEmployees>()
{
new NorWindsEmployees(){ EmployeeName ="A",ImageName = "China_Flag.jpg"},
new NorWindsEmployees(){ EmployeeName ="B",ImageName = "du.png"},
new NorWindsEmployees(){ EmployeeName ="C",ImageName = "Kiron.gif"},
};
}
Output:
Note: If you would like to know more details on it you could check our official document here.