Writing Raw HTML in Blazor Views

Robert McLaws
CloudNimble
Published in
1 min readNov 24, 2019

I was wrapping up the last-minute details for the launch of Azure DevOps Buddy a few days ago, and I came across a situation where I wanted to take a string that had formatted HTML in it and write the formatted result to the view.

I’m sure you’ve been in this type of situation before:

@(vm.AppState.TrialEnds != DateTimeOffset.MinValue ? $"<strong>Your trial ends on {vm.AppState.TrialEnds.DateTime.ToShortDateString()}.</strong> " : "")

Notice in this ternary statement, the first condition has a <strong> tag. In MVC, you’d change the beginning to @Html.Raw() and be on your merry way.

But the solution in Blazor is not obvious. Instead, you have to cast it to a MarkupString. So it looks like this:

@((MarkupString)(vm.AppState.TrialEnds != DateTimeOffset.MinValue ? $"<strong>Your trial ends on {vm.AppState.TrialEnds.DateTime.ToShortDateString()}.</strong> " : ""))

Note that if you use it in a ternary statement, you have to wrap that statement in parenthesis as well, otherwise you’ll get red squigglies and it won’t compile.

Hope that helps!

PS: If you want to try out our first Blazor + Electron desktop app, sign up for the Azure DevOps Buddy Beta!

--

--

Robert McLaws
CloudNimble

Founder & CEO of BurnRate (@BurnRate_io). Serial entrepreneur. Former Microsoft MVP. @dotnetfdn member. Helping founders build amazing businesses.