Search code examples
c#razorblazor

Is there a way to execute code in blazor component inside html tags?


What I am would like to do is something like this:

<input type="text"
@if(!String.IsNullOrEmpty(Element.Placeholder))
{
   placeholder="@Element.Placeholder"
}
/>

And I want to do that with many properties like maxlength, value etc. The best solution I came up with is using MarkUpString to do the above and then render it. I was wondering if there is a way to use if's inside an html tag so my code will be cleaner and easier to modify. Please be lenient, I'm new to programming and especially Blazor. Thanks

*Edit: I want this component to be editable from another component too.


Solution

  • You can use @attributes. I've shown a very simple code example below setting the style.

    <button @attributes="this.ButtonAttributes">Red Button</button>
    
    @code{
    
      private Dictionary<string, object> ButtonAttributes = new Dictionary<string, object>();
    
      protected override Task OnInitializedAsync()
      {
        ButtonAttributes.Add("class", "btn btn-danger");
        return Task.CompletedTask;
      }
    
    }