This project is read-only.

PagedSortedViewModel with Auxiliary Data Model Tutorial

This tutorial shows you how to use an auxiliary data model with a PagedSortedViewModel. The tutorial assumes you know C# and ASP.NET MVC, and you're familiar with the contents of the Basic Sorter and Paging Tutorial.

It's quite a common occurrence that you'd need to pass extra data to the View alongside the sortable data that you're going to put in your sortable table. The PagedSortedViewModel<T, TAuxModel> class lets you do this.

Imagine you wanted not only to show a sortable, pageable table of employees, but you also wanted to display some stats about them, for example:

public class EmployeeStats
{
    public Employee TopEmployeeForMonth { get; set; }
    public Employee TopEmployeeForYear { get; set; }
}

Your action method in the employee controller would now look like this:

public ActionResult Manage(int? page, [ModelBinder(typeof(EmployeeSorterBinder))] Sorter<Employee> sort)
{
    int totalPages = PagedDataHelper.GetTotalPages(_EmployeeManager.CountEmployees(), PAGE_SIZE);
    page = PagedDataHelper.ValidatePage(page, totalPages);

    IList<Employee> employees = _EmployeeManager.GetEmployees(page.Value, sort);
    EmployeeStats stats = _EmployeeManager.GetEmployeeStats();

    return View(new PagedSortedViewModel<Employee, EmployeeStats>(employees, sort, page.Value, totalPages, stats));
}

Notice how we're now using a PagedSortedViewModel that has a second type parameter (TAuxModel) and an extra constructor parameter? This is the other PagedSortedViewModel type that you can use that allows you to have that extra data alongside the paged/sorted data.

In the View we'll need to change the Page directive to reflect this:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<PagedSortedViewModel<Employee, EmployeeStats>>" %>

Now we can access that auxiliary data in the View via the Model.AuxModel property like so:

<p>
    <strong>Employee of the Year:</strong>
    <%= Html.Encode(String.Format("{0} {1}", Model.AuxModel.TopEmployeeForYear.FirstName, Model.AuxModel.TopEmployeeForYear.LastName)) %>
    <strong>Employee of the Month:</strong>
    <%= Html.Encode(String.Format("{0} {1}", Model.AuxModel.TopEmployeeForMonth.FirstName, Model.AuxModel.TopEmployeeForMonth.LastName)) %>
</p>

Last edited Mar 24, 2010 at 12:04 PM by dchambers, version 1

Comments

No comments yet.