user101289
user101289

Reputation: 10422

Blazor ternary operator with HTML as result

I'm working with Blazor after a long time doing react, and I'm really not understanding how (as far as I can tell) Blazor has very limited ability to compose HTML results dynamically in the code. For a simple example, I have a user profile and I want to show an icon / badge to demonstrate the inactive status of the user. What's the "right" way to do this? I have something like this (in pseudo code since I can't seem to get the interpreter to accept my attempts):

@(UserViewModel.IsInactive == true ? "<i class=\"ps-2 fas fa-seal-exclamation\" style=\"color: yellow\" title=\"Inactive\"></i>" : "")

This just returns the actual HTML however, it doesn't render it.

Another similar situation I'm seeing a lot is conditionally displaying a line of text, like if the address exists, display it but otherwise don't show the line:

@(UserViewModel.Address?.Address1 ? UserViewModel.Address.Address1 + "<br/>" : "")

This works but seems a little awkward-- is it possible to do a function in the code-behind C# page (MyComponent.blazor.cs) that would just return the rendered HTML? If it is possible I haven't found the right return type for it, and it always errors out. In react I would compose many little helper functions to return HTML based on a parameter or object passed in-- I don't see how to do that in Blazor.

Upvotes: 3

Views: 2427

Answers (1)

Surinder Singh
Surinder Singh

Reputation: 1458

Try this

@if(UserViewModel.IsInactive)
{
    <i class="ps-2 fas fa-seal-exclamation" style="color: yellow" title="Inactive"> 
    </i>
}

Upvotes: 7

Related Questions