Reputation: 229
I want to do an "image gallery" in my Blazor Server App. For each Filepath it should create an <img src="@file"/>
element containing the filepath in the local variable "file".
Now it throws me this error: MissingMethodException: Cannot dynamically create an instance of type 'Photobx.Pages.Index'. Reason: No parameterless constructor defined.
My files are in wwwroot/pics .
Here is my code:
index.razor
@foreach(string file in filepaths)
{
<img src="@file"/>
}
@code {
private IWebHostEnvironment Environment;
public List<string> filepaths = new List<string>();
public Index(IWebHostEnvironment _environment)
{
Environment = _environment;
}
public void GetFilePaths()
{
foreach(string file in Directory.GetFiles(Path.Combine(this.Environment.WebRootPath, "pics/")))
{
filepaths.Add(file);
Console.WriteLine(file + " was added");
}
}
protected override void OnParametersSet()
{
GetFilePaths();
}
}
Upvotes: 1
Views: 583
Reputation: 11392
You cannot inject parameters to a Blazor component from the constructor.
You can use the @inject
razor directive
@inject IWebHostEnvironment Environment
@foreach(string file in filepaths)
{
<img src="@file"/>
}
...
or [Inject]
attribute when using code-behind approach.
public class ComponentBase : IComponent
{
[Inject]
protected IWebHostEnvironment Environment { get; set; }
}
Check microsoft documentation for more information regarding this topic.
Upvotes: 4