Skip to main content
Home  ›  Blog

Razor Tip of the Day - Shared Library of Methods and Values Across Views (200)

Using Razor to create templates and views is very simple, elegant and easy to understand. But when you want to share a few lines of code, a function or some constants between views, you need a simple trick.

No DLLs - good and bad

Basically when we're just working with razor, then there is no officially compiled code. In reality, every Razor is also compiled to code - but this is background-magic outside of your control. So to share a few lines of code, we do the following.

Create a "shared" file

Remember to name it with "_" at the beginning, to prevent the file from ever being accessed directly through the web. Now place some code in - inside an @function block - which will be reused. This example shows the shared bits of the Blog App in the "_library.cshtml":

_library.cshtml (the shared library)

@using System.Dynamic
@functions {

	public dynamic unknownAuthor = ToExpando(new Dictionary<string, object>() 
		{
			{ "FullName", "Unknown" },
			{ "Image", "unknown.jpg" },
			{ "ShortBio", "bio unknown" }
		}); 
}

Accessing the Shared file

To access the shared file, we ask Razor to create the object for that file, and then we can just access the methods, properties, functions etc. like this:

_list-item.cshtml (a library user)

@{	var lib = CreateInstance("_library.cshtml"); }
@{
    var author = (post.Author.Count > 0) ? post.Author[0] : lib.unknownAuthor;
}
...

Shared Partial Templates/Snippets

In  shared "library" you could also have functions which render html-snippets. But this is not really the recommended way to do it, as it's better to use shared sub-templates - which I'll explain in the next Tip of the Day on sharing views.

Love from Switzerland,
Daniel


Daniel Mettler grew up in the jungles of Indonesia and is founder and CEO of 2sic internet solutions in Switzerland and Liechtenstein, an 20-head web specialist with over 800 DNN projects since 1999. He is also chief architect of 2sxc (see github), an open source module for creating attractive content and DNN Apps.

Read more posts by Daniel Mettler