How to Use Style Attribute

Hello Guys, in this quick example we’ll see how to use Style attribute in Blazor Foundation. Take note that, we are using Newtonsoft JSON Objects for everything that requires passing a dictionary of dynamic object like JSON.

Therefore, to pass a custom style to an object in Blazor Foundation, you have ~2 Good ways to do it.

Method #1

The method one is pretty straight forward. Import Newtonsoft and Inline the creation of the object.

using Newtonsoft.Json.Linq;

We can create the JObject inline. The example below will pass to the button a margin of 1px and a padding of 1px. You can pass any CSS setting available.

<Button Style="@(new JObject() { { "margin", "1px"}, { "padding", "1px"} })">
  
</Button>

Method 2

The method 2 is very useful when we are working with states or when we want to build a more complex css.

using Newtonsoft.Json.Linq;

In the example below, we will create JObject not inline and we will assign it to the component.

<Button Style="@MyStyle">
  
</Button>

@code {
	public JObject MyStyle = new JObject() { {"display","block"} }; // You can assign here or like below
    
	protected override async Task OnInitializedAsync()
    {
    	// Adding to MyStyle on Load
        MyStyle.Add("margin", "1px");
        MyStyle.Add("padding", "1px");
    }
}

Thats it! Simple Enough?… You just learned how to use style attribute in Blazor Foundation.