Integrating MarkdownSharp and Pagedown into your MVC App

Mick B
2 min readOct 29, 2017

One of my apps uses Markdown for content editing, just like StackOverflow. Fortunately, the folks over at SO decided to open-source their code for that feature set. It’s broken into two parts:

  1. MarkdownSharp: Serverside markdown compiler
  2. Pagedown: Clientside markdown converter/preview generator

So, why do we need both of these?

Well, you could just stick with pagedown, store the markdown in your server, and serve the markdown back up to browsers for them to render every time they load some markdowned content. But there are a few problems with this:

  1. Search engines won’t see the content since they don’t run the JS you’ll need to convert the markdown to html
  2. Users without JS won’t even be able to read your site’s content for the same reason
  3. Do you really want to use your browser’s precious resources compiling html for every view?

You can use Pagedown on the client to actually compose your markdown, and then shoot it off to a serverside controller that compiles valid html using MarkdownSharp. Store both versions in the db. Why store both? Well, for view-only access, you just need the generated html. But what if you allow your users to edit their content? Then you need to pull up the original markdown.

Ok, now for the implementation. Here are the steps:

Clientside — Pagedown

  1. Get your textbox ready:

2. Include Markdown.converter.js, Markdown.Sanitizer.js, and Markdown.Editor.js in your solution, along with wmd-buttons.png and the css from demo.css

3. Add the js from demo.html to your page’s js — this hooks up the pagedown functionality. Make sure you either use onReady or ensure that the js loads after your elements are ready.

4. Tie the wmd-input, wmd-button-bar, and wmd-preview ids up like demo.html. Optionally include the CSS.

5. Enjoy clientside markdown:

Serverside — Markdown

1. Copy the Markdown.cs file into your project

2. Instantiate that and use it to store html alongside your raw text:

private readonly Markdown _compiler; 
_compiler = new Markdown {
AutoHyperlink = true, AutoNewLines = false
}; // I do this in a BaseService
string html = _compiler.Transform(newPost.Content);

Thanks for reading!

Mick

--

--