Using ASP.Net Webpage Helpers
The ASP.Net team at Microsoft has released a package of helpers that can be used in all ASP.Net applications. These helpers work in MVC but they also work in ASP.Net Web pages as well. The team at Microsoft is able to update and modify these helpers and publish them using NuGet much quicker than they used to when they had to coordinate their release with the entire Visual Studio product. Let's take a look at how to install these helpers using the NuGet console window. Then we will use some of the helpers in a project.
To bring up the NuGet console window, go to the Tools menu, then Library Package Manager, and then Package Manager Console, as seen in Figure 4. This will open a new window in the Visual Studio IDE.
To install a package using the Console, type the command
install-package microsoft-web-helpers. This will invoke the
install-package command, passing in the package ID
microsoft-web-helpers. NuGet will download and then reference an assembly in your project. See Figure 5 for the output of the Console window.
The first example will use the Twitter helper to show a search of Twitter on an MVC View. Create a new View and reference the helpers by adding a
using Microsoft.Web.Helpers directive. Next, call the Twitter helper, using the
Search method as shown here:
@using Microsoft.Web.Helpers <h2>@ViewBag.Message</h2> <p> @Twitter.Search("MVC3iA",width:800,title:"MVC3 in Action Tweets") </p>
Running this in the browser will show the client-side Twitter widget that queries Twitter for the search term "MVC3iA." See Figure 6 for the screen shot of the page.
This was a really simple way to add some canned functionality into an application with almost no effort. Next, let's look at another helper available in this library.
LinkShare is a helper that will draw the icons and add links so that a user to your page or site can easily share the URL using the popular social networking sites. You could do this by yourself, but using the helpers lets you do it quickly.
After creating a new Action and View, add the
using directive to the top of the view code. Use the
LinkShare helper to create a helper on the View:
<h2>LinkShare</h2> @LinkShare.GetHtml("MVC 3 in Action")
There it is a quick widget that gives your app social network sharing with a simple helper. Using the code is simple, but the enabler for this is really the power of NuGet and how it makes finding and adding libraries to your project frictionless.
Components like Microsoft Web Helpers let us add new functionality to applications and Web pages quickly and easily. They're even easier to use with NuGet, which turns hours of downloading, reading "getting started" docs, and debugging through configuration into a few seconds of automation.
Jeffrey Palermo, Jimmy Bogard, Eric Hexter, Matthew Hinze, and Jeremy Skinner are the authors of ASP.NET MVC 3 in Action, published by Manning. This article is based on Chapter 5 of the book.