Tom Archer's Blog

Windows and Web developer with Social Media tendencies

View Components in ASP.NET 5

ASP.NET 5 View Components – like ASP.NET Partial Views – enable you to create a kind of mini-controller capable of rendering a partial response to the client rather than a whole response. This is especially useful for situations where you want to display some dynamic data to your user on multiple pages. For example, a store app could display it’s best selling or on-sale items on every page with links to a Deals page. An LOB app might need the ability to display system warnings on each page. This post is a quick introduction to how to set up and use a View Component in ASP.NET 5.

To add a View Component to an ASP.NET 5 app, simply follow these steps:

  1. Create the View Component
  2. Create the View Component’s view
  3. Call the Component.Invoke

Create the View Component

To create a View Component, first create a C# class and either derive it from ViewComponent or decorate it with the ViewComponent attribute.

...
using Microsoft.AspNet.Mvc;

namespace MyStore.Models
{
  public class User
  {
    public string Name { get; set; }
  }

  public class UsersOnline : ViewComponent
  {
    public IViewComponentResult Invoke ()
    {
      // In-memory structure to keep example simple.
      // In a real-world app, this data would come from a 
      // data store such as a database.
      IList<Item> users = new List<User>()
      {
        new User() { Name = "Krista" }
        new User() { Name = "Tom" }
      };

      return View(users);
    }
  }
}

Create the View Component’s view

Next, create the view that will be displayed when the View Component is rendered.

@model IEnumerable<MyStore.Models.User>

<h3>Other online users</h3>
<ul>
@foreach (var user in Model)
{
  <li>@user.Name</li>
}
</ul>

Call Component.Invoke

The last step is to call the Component.Invoke method wherever you want to display the View Component.

@Component.Invoke("UsersOnline")

Summary

View Components are just one of the many new great features in ASP.NET 5 that make your coding life just a little bit easier. Check out the http://docs.asp.net for more detailed articles on this feature any many others.

Related Links

Advertisements

September 26, 2015 - Posted by | aspnet5

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: