Aspnetcore: How to add multiple styles using the IDictionary<string, object> in Blazor attributes ?

Created on 3 Oct 2019  路  3Comments  路  Source: dotnet/aspnetcore

Below is the code blow which throws an exception as this key value already exists.

"

"

@code {
private IDictionary _Attributes = new Dictionary();

// This adds to the element
_Attributes.Add("style", "width:" + this.width);

// This throws an exception that the key value already exists
_Attributes.Add("style", "height:" + this.height);
}

Can anyone suggest a solution for this to achieve in any other way.?

area-blazor question

All 3 comments

Thanks for contacting us, @Indrajith-Sync.
Attribute Splatting (the @attributes directive) is meant to be used for applying different attributes to an element. In this case you're trying to apply multiple sub-values to the same style attribute.
You have two options here, either concatenate both width and height pieces into a single string when applying to style (using the attribute splatting technique), or directly set the style attribute on the div.

Here is a sample:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.
<div @attributes="attributes">option 1</div>
<div style="@Style">option 2</div>

@code{
    public IDictionary<string, object> attributes = new Dictionary<string, object>();

    public string Style { get; set; }

    public int Width { get; set; } = 300;
    public int Height { get; set; } = 15;

    protected override void OnInitialized()
    {
        this.Style = $"width: {Width}px; height: {Height}px; border: 1px solid red;";

        this.attributes.Add("style", this.Style);
    }
}

Hi @mkArtakMSFT

Thanks it works fine..!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

guardrex picture guardrex  路  3Comments

rynowak picture rynowak  路  3Comments

Kevenvz picture Kevenvz  路  3Comments

farhadibehnam picture farhadibehnam  路  3Comments

markrendle picture markrendle  路  3Comments