Skip to content

A Razor ‘@helper’ block for .NET Core

Joe Glombek asked me to elaborate on this toot:


TIL: The “holy-cow-I-used-that-a-lot” @​helper feature in Razor that was removed [at some point], does in fact still exist, albeit a whole lot more anonymously (which of course means that I would never find out about it on my own).


What I was referring to was this Razor feature that I’ve been using a lot:


@helper sayHello(string name) {
	var greeting = name == "Joe" ? "Hello!" : "Hi there!";

The idea being that you could create what’s essentially a function, but instead of returning a value, it renders markup directly from within; i.e. no HtmlString-futzing necessary to build a return value.

But this was no longer possible in .NET Core, and I’ve been back to creating real functions, returning HTMLStrings, when I saw something very similar in a C# View Partial:

	void QuoteMe(string message, string source) {
		<q cite="@(source)">@(message)</q>

Apparently that’s been possible since .NET Core 3/4-ish?