Markdown in Your MVC 6 Razor Pages


Originally posted to:

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

Taylor Mullendemoed the idea of a Markdown Tag Helperidea 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.

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

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 markdownattribute:

<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")][HtmlTargetElement("markdown")][OutputElementHint("p")]public class MarkdownTagHelper : TagHelper{public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output){if (output.TagName == "markdown"){output.TagName = "p";}var childContent = await context.GetChildContentAsync();var markdownContent = childContent.GetContent();var markdown = new MarkdownSharp.Markdown();var htmlContent = markdown.Transform(markdownContent);output.Content.SetContentEncoded(htmlContent);}}

You can grab the code from GitHubor install the package using Nuget.

Install-Package TagHelperSamples.Markdown

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