04 Nov 2025
Download as Markdown file using Blazor WASM and JavaScript.
Here is the full solution:
Blazor Component
<button class="btn" title="Save as Markdown file" @onclick="DownloadAsMarkdownAsync">
<span class="bi bi-filetype-md"></span>
</button>
@code {
[Inject]
private IJSRuntime JsRuntime { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
await JsRuntime.InvokeVoidAsync("import", "./module.js");
}
private async Task DownloadAsMarkdownAsync()
{
string filename = "example.md";
string markdownText = "# Example Markdown\nThis is some example text.";
await JsRuntime.InvokeVoidAsync("Module.downloadAsMarkdown", filename, markdownText);
}
}
JavaScript Code
export class Module {
static downloadAsMarkdown(filename, text, mimeType = 'application/octet-stream') {
var blob = new Blob([text], { type: "text/markdown" });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.dataset.downloadurl = ["text/markdown", mimeType].join(":");
a.click();
}
}
window.Module = Module;
What's happening:
We're creating a Blazor component that has a DownloadAsMarkdownAsync method. This method is responsible for downloading some sample markdown text as an .md file.
To achieve this, we need to call a JavaScript function from our C# code. We've created a JavaScript class called Module with a static method called downloadAsMarkdown. This method takes three parameters: the filename to download, the markdown text to download, and an optional mimeType parameter.
In the Blazor component's DownloadAsMarkdownAsync method, we're calling the downloadAsMarkdown JavaScript function using the InvokeVoidAsync method. We pass in the filename and markdown text as parameters, but not the mimeType. This is because the downloadAsMarkdown function has a default value for mimeType, which is 'application/octet-stream'.
The JavaScript code creates a blob with the markdown text and sets up an anchor element to download it. The a.dataset.downloadurl property is set to include both the file type (text/markdown) and the mimeType. Finally, we click the anchor element to initiate the download.
Key takeaways:
InvokeVoidAsync method to call a JavaScript function from our C# code.mimeType parameter with a default value.filename and markdownText) to the JavaScript function, relying on its default value for mimeType.Every now and then I have to prioritize work, life or other matters but we'll soon continue with the ML Basics on YouTube
Kind regards, Auguste @ kiss-code
I continuously build, learn and experiment with innovative technology. Allow me to share what I learn, with you.