Create Markdown editor in Blazor Application

Markdown is a text-to-HTML conversion tool for web writers. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML).

Nowadays, Markdown is a very popular technology for creating web editors. StackOverflow uses MarkDown editor on their QnA website. There is a lot of online markdown editor available, like stackedit is very popular.
This blog post will show you how to create a markdown editor in the Blazor Application.

Let's start with some basic HTML structures. I have created a bootstrap row and two columns the first column is the input area, and the second column will show the preview.

<div class="row">
    <div class="col-6">
        <textarea class="form-control"></textarea>
    </div>
    <div class="col-6">
       ==Preview==
    </div>
</div>

Bind your inputs to something

Now we're ready to take the next step; we need to take whatever is entered into the textarea and store it in our component's state.

For this, we can use properties and Blazor's binding syntax. We just need to declare a couple of attributes:

<div class="row">
    <div class="col-6">
        <textarea class="form-control" @bind="Body" 
       @bind:event="oninput" ></textarea>
    </div>
    <div class="col-6">
        @(StringToMarkdown)
    </div>
</div>
@code {
    public string Body { get; set; } = string.Empty;
    private string html="";
    public string StringToMarkdown;
 
}

From markup to HTML

Till now, we have not added anything related to Markdown. To convert text to HTML, we don't need to expend much effort to get HTML from this markup, and we can employ the excellent Markdig .NET Markdown processor to do it for us.
Let's add the NuGet package to our project by running the following command

Install-Package Markdig

Once the NuGet package is installed. Let's add a new StringToMarkdown property to our component, which will invoke Markdig every time we request its value.

@using Markdig
<div class="row">
    <div class="col-6">
        <textarea class="form-control" @bind="Body" 
       @bind:event="oninput" ></textarea>
    </div>
    <div class="col-6">
        @((MarkupString)StringToMarkdown)
    </div>
</div>
@code {
    public string Body { get; set; } = string.Empty;
    private string html="";
    public string StringToMarkdown{

        get{
            try{

                html=Markdown.ToHtml(Body);
            }
            catch{

            }
            return HTML;
        }
    }

    

}

Live Demo

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru