Markdown in your ASP.NET Core Razor Pages

What? Markdown in your Razor code? Yeah…and it was totally easy to build too.

Taylor Mullen demoed the idea of a Markdown Tag Helper idea at Orchard Harvest and I thought it would be nice to include this in my Tag Helper Samples project.

How to use it

This tag helper allows you to write Markdown directly in Razor and have that automatically converted to HTML at runtime. There are 2 options for how to use this tag helper. The first option is to use a <markdown> element.

<markdown>This is some _simple_ **markdown**.</markdown>

The tag helper will take this and convert it to the following HTML:

<p>This is some <em>simple</em> <strong>markdown</strong>.</p>

The other option is to use a <p> element that has the markdown attribute:

<p markdown>This is some _simple_ **markdown** in a _p_ element.</p>

The tag helper uses MarkdownSharp, which supports most of the markdown syntax supported by Stack Overflow.

How it works

The implementation of this tag helper is surprisingly simple. All we do is grab the contents of the tag and use MarkdownSharp to convert that to HTML.

[HtmlTargetElement("p", Attributes = "markdown")]
public class MarkdownTagHelper : TagHelper
public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)

if (output.TagName == "markdown")
output.TagName = null;

var content = await GetContent(output);
var markdown = content;
var html = CommonMarkConverter.Convert(markdown);
output.Content.SetHtmlContent(html ?? "");

Try it yourself

You can grab the code from GitHub or install the package using Nuget.

Install-Package TagHelperSamples.Markdown

Give it a try and let me know what you think.