You're on the right lines. Forget the Javascript, you're in Blazor. I can't see where your using this image so I can't talk specifics, but you need to think component - what is my user display thing. How do I make it a component - everything in the Blazor UI is a component!
To make this easier to demo, I'll set the background color rather than the image on a component.
Create a Razor component - MyBackground.razor
<div style=" background-color:@this.Color" @attributes="Attributes">
@ChildContent
</div>
@code {
[Parameter] public string Color { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; }
private IDictionary<string, object> Attributes
{
get
{
var attr = "style";
if (this.AdditionalAttributes != null)
if (this.AdditionalAttributes.ContainsKey(attr)) this.AdditionalAttributes.Remove(attr);
return AdditionalAttributes;
}
}
}
You can then use this - I've added it to Index.razor in the standard template
@page "/"
@using TestBlazorServer.Components
<MyBackground Color="@this.color" class="p-5" style=" background-color:black">
<h1 class="border-primary">Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
</MyBackground>
@code{
private string color { get; set; } = "#bbf";
}
I've added some extra attributes so you can see how these are handled by the component. class gets passed through, while style get removed - the background is blue not black with a nice wide padded margin.
The base code for your component would look something like:
<div style="background-image:@this.ImageUrl" @attributes="Attributes">
@ChildContent
// Or Html code to build out my UserDisplay Component
</div>
@code {
[Parameter] public string ImageUrl { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; }
private IDictionary<string, object> Attributes
{
get
{
var attr = "style";
if (this.AdditionalAttributes != null)
if (this.AdditionalAttributes.ContainsKey(attr)) this.AdditionalAttributes.Remove(attr);
return AdditionalAttributes;
}
}
}
Put any specific component CSS in a component CSS file. MS Docs on Component CSS