How to add inline html with Blazor c#

Viewed 940

New to Blazor and having issues getting inline html added.

I'm trying to update an old practice solution and this is what I have there:

<a href="#" @(Model.SideNavHasTooltips ? "tooltip=" + @item.Name + " flow=right" : string.Empty)>

That would generate something like

<a href="#" tooltip="abc" flow="right">

With Blazor, I'm having more difficulty doing this and not sure if I'm missing something obvious?

<div @(SideNavHasTooltips ? "tooltip=" + @item.Name + " flow=right" : string.Empty)>

I've tried adding it to a variable and using that and tried a few other ideas, all to no avail.

I'm really not sure what the right way to do this is but it's not the same so any advice would be helpful.

Thanks

2 Answers

You can make use of Attribute splatting and arbitrary parameters using the @attributes parameter.

<div @attributes="@TooltipAttributes(item.Name)"></div>

In your code you need a method like:

IDictionary<string, object> TooltipAttributes(string itemName)
 {
   return SideNavHasTooltips 
          ? new Dictionary<string, object>() 
            {{ "tooltip", itemName }, {"flow","right"}} 
          : new Dictionary<string, object>() { };
 }

This will then generate the tag:

<div tooltip="the_name_you_gave_it" flow="right"></div>

or if SideNavHasToolTips is false

<div></div>

The @attributes takes a dictionary of string, object.

Alternatively you could do it inline:

<div @attributes="@( SideNavHasToolTips ? new Dictionary<string, object> { {"tooltip", item.Name},{"flow","right"} } : new Dictionary<string, object> { } )"></div>

If its just html could make use of the MarkupString class

@(new MarkupString( "<div " + (SideNavHasTooltips ? $" tooltip=\"{item.Name}\" flow=right":"")+ ">" ))
Related