Feliz.ViewEngine with MVC in F#

jkone27
3 min readMar 25, 2021
F# logo

We will be creating a simple HTML View rendered in memory in a single MVC controller, where HTML and CSS will also be strongly typed (as code).

We won’t need any external .cshtml or .html file as F# allows HTML to be expressed within a very idiomatic style using Feliz.ViewEngine DSL as static functions and list parameters.

E.g. this HTML div:

<div class="my-class">HELLO</div>

simply becomes a standard F# function invocation from a static Html module:

Html.div [ 
prop.className "my-class"
prop.text "HELLO"
]

Giraffe has a similar html templating DSL but it’s a bit more verbose, so I go for Feliz as it looks a lot like actual HTML.

Getting Started

You will need the .NET sdk or latest visual studio installed.
If you don’t have visual studio for whatever reason (you are on linux or mac) you can use ionide and vscode, or vs for mac, or rider.

First create a new aspnet F# MVC application, or you can follow some guidance from this previous post I made (there are a bit more details, if it’s too much feel free to skip it).

Create a new folder and with your favorite terminal write

dotnet new mvc -lang f# && dotnet run

Adding to an existing aspnet mvc solution (opt)

If you are not starting from the microsoft template (step above) for any reason, you will need to add this library and this line of code to your Startup.cs code.

You can skip this part if you use the template in the previous step.

In place of the line for .AddControllers in your startup file, replace that call with this one here:

services.AddControllersWithViews().AddRazorRuntimeCompilation()

and add to your project file as well this nuget package

dotnet add package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

then all you have to do is add a couple of nuget packages to your MVC project

dotnet add package Feliz.ViewEngine
dotnet add package Zanaptak.TypedCssClasses

Adding the in-memory View Controller

Now add a special controller, which will act as a view controller only as the whole HTML will be there in code, thanks to Feliz.ViewEngine.

Good news, no need for separate .cshtml or .html files, nor any special runtime/dynamic routing conventions (for which MVC usually relies on)

Views/[ControllerName]/[ViewName].cshtml

As a known downside, this is all server side rendering of the page, so you should use it only in scenarios which allow this kind of approach.

The generated HTML response

This is the generated view (HTML), then you can start getting fancy with your CSS and HTML skills!

Generated HTML

Feel free to use and experiment with the CSS library you prefer.

The amazing Css type provider will do an awesome job at always giving you type-safe CSS string properties to use, and will act as an online documentation!

Feliz has already an implementation for Bulma CSS view engine as well, and even other UI frameworks are available.
Check it out on Feliz docs!

--

--