Search code examples
c#asp.netrazorrazor-2

Import Razor @helper from Class Project


Is there a way to import a dll from a class project (or maybe another web application project) into a web application project and reuse a @helper? The reusability for web applications with Razor seems pretty much zero if that cannot be achieved.


Solution

  • You can do it, but you have to jump through several hoops.

    1. You need to obtain RazorGenerator: "This is a Custom Tool for Visual Studio that allows processing Razor files at design time instead of runtime, allowing them to be built into an assembly for simpler reuse and distribution. "

    2. Using RazorGenerator, you can create .cshtml files in your class library project that declare helper functions. For example, in a file called Foo.cshtml:

      @helper MyHelper(string parameter) {<text>@parameter</text>}
      
    3. These helpers will exist as static methods in the static class representing your .cshtml file. In the above example, that would translate to Foo.MyHelper.

    4. You can invoke these static methods from your web application's .cshtml file just like any other static method. (assuming you've added the correct using directives to point to the namespace containing your helper.) For example:

      <div>@Foo.MyHelper("hello world")</div>