Razor Helpers

Razor Helpers provide an easy way to define common Razor markup in one centralized location and reuse that markup across your site. You can think of them much like global methods, except that Razor markup offers the ability to mix code and HTML markup rather than containing just code. Luckily, creating and using Razor Helpers is very simple and straightforward.

The easiest way to begin writing a Razor Helper is to choose an existing Razor page in your site, and then write and test the Razor markup that you wish to reuse. To demonstrate, let’s modify the blog site’s Post markup, adding a link to the template for each of the blog posts that allows visitors to share a direct link to the post via Twitter. The HTML for creating this button, as copied from Twitter’s developer website, is as follows:

<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
<div>
   <a href="http://twitter.com/share" class="twitter-share-button"
      data-url="http://dev.twitter.com/pages/tweet_button"
      data-text="Checking out this page about Tweet Buttons">Tweet</a>
</div>

After inserting the Twitter markup, the _Post.cshtml partial view looks like this:

@{ var post = Page.Post; var url = "http://www.myblog.com/posts/post.cshtml?id=" + post.ID; } <div> <h3>@post.Title</h3> <div>@post.Body</div> <script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script> <div> <a href="http://twitter.com/share" class="twitter-share-button" data-url="@url" data-text="@post.Title">Tweet</a> ...

Get Programming Razor now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.