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:
simply becomes a standard F# function invocation from a static Html module:
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.
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:
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)
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!
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!