April 19, 2018 by Anuraj
ASP.NET Core Razor
This post is a small tip about reusing HTML snippets inside a Razor view in ASP.NET Core. In earlier versions of ASP.NET MVC this could be achieved with the help of helper - A helper is a reusable component that includes code and markup to perform a task that might be tedious or complex. But there is no equivalent implementation is available in ASP.NET Core MVC. In this post I am explaining how we can achieve similar functionality in ASP.NET Core. Unlike ASP.NET MVC, this implementation, you can’t use it in multiple page. This is very helpful if you want to do some complex logic in view.
To implement this, first you need to create a function in Razor, you can do like this. I am using the same function which is used in @helper documentation in MSDN.
This function accepts a string and returns
IHtmlContent interface. The
string argument you can access with
@item. And you can use the function like this. -
@MakeNote("My test note content.")
You can have only one input parameter, for multiple parameters you need to use complex object something like this.
And you can use it like this -
To make it available in different page, I tried it in _layout.cshtml and _viewstart.cshtml but both didn’t worked. :(
Happy Programming :)