You're heading in the right direction. Forget about Javascript, because you're working with Blazor now. I'm not sure where you plan to use this image, so I can't provide specific guidance. But remember, in Blazor, everything in the UI is a component!
To make it simpler for demonstration purposes, let's set the background color on a component instead of using an image.
Start by creating a new Razor component called 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 utilize this component - 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 included some additional attributes to showcase how they are handled by the component. The class
attribute is passed through, while the style
attribute is removed, resulting in a blue background instead of black with ample padding.
The basic code structure for your component would resemble:
<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;
}
}
}
Remember to place any specific component CSS in a separate component CSS file. For more information, refer to MS Docs on Component CSS.