Pier-Luc Bonneville
Pier-Luc Bonneville
Creator of this blog.
Mar 14, 2021 2 min read

Introducing the .NET Interactive Notebooks Razor extension

thumbnail for this post

As seen in my last post, we looked into different ways to display HTML with values from variables in the dotnet kernel.

  1. Using the #!html and #!js magic command.
  2. Using the PocketView API.
  3. Using the HtmlContentBuilder class.

None of these options feel natural to me. Turns out there is an easier way to achieve the same result: Razor in .NET Interactive Notebooks!

Getting started

To get started with Razor in .NET Interactive Notebooks, first install the RazorInteractive NuGet package.

In a new C# (.NET Interactive) cell enter and run the following:

#r "nuget: RazorInteractive, 1.0.0"

That’s it!

You are now ready to use the dotnet kernel Razor extension to display your standard HTML and mix it with C# as you would do in a regular MVC, Razor Page, or Blazor application.

Using the #!razor magic command your code cell will be parsed by a Razor engine and the results displayed using the "txt/html" mime type.

Here is an example of Razor markup being parsed and rendered in Jupyter Notebook.

using the razor magic command

The same can be done using .NET Interactive Notebooks in Visual Studio Code.

using the razor magic command

Accessing the variables

The dotnet kernel variables are all available through the @Model property.

using the razor magic command with variables - example 1

Again, the same can be achieved using .NET Interactive Notebooks in Visual Studio Code.

using the razor magic command with variables - example 2

Conclusion

After using Razor for close to a decade, I’m happy I can continue using this proven markup syntax in .NET Interactive Notebooks.

Happy rendering!

The code for the RazorInteractive NuGet package is available here:

RazorInteractive

References

  1. .NET Interactive - GitHub
  2. Razor syntax reference for ASP.NET Core