part 03 – sorting, paging, and grouping entity framework ntpcug tom perkins

45
Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Upload: karin-charles

Post on 17-Dec-2015

222 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Part 03 – Sorting, Paging, and Grouping

Entity FrameworkNTPCUG

Tom Perkins

Page 2: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Previously …

• Contoso University solution created• Database• Student Model, Views, and Controller• CRUD Scaffolding

Page 3: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Session Objectives

1. Sorting – display student data in different orders by clicking on the column headings.

2. Filtering – Search student names that contain a string of characters

3. Paging – Show pages of a long list of students4. Grouping – Show student statistics derived

through grouping

Page 4: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Target “Students” Page

Page 5: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

COLUMN HEADER SORT LINKSObjective 1

Page 6: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Column Headings

• Headings: Last Name and Enrollment Date• Click on heading to sort list• Repeated clicking – toggles list in ascending

versus descending order• Headings are hyperlinks to a controller action

Page 7: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Student Activity

• Open Visual Studio• Open the Contoso University solution• In the Solution Explorer

– In the Controllers section,• Click on StudentController.cs

• Locate the Index method• Replace the code in the Index method by cutting and

pasting the code in Part 3 Timesaver Modification 1 // GET: /Student/ public ActionResult Index() { return View(db.Students.ToList()); }

Page 8: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

public ActionResult Index(string sortOrder){ ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; var students = from s in db.Students select s; switch (sortOrder) { case "name_desc": students = students.OrderByDescending(s => s.LastName); break; case "Date": students = students.OrderBy(s => s.EnrollmentDate); break; case "date_desc": students = students.OrderByDescending(s => s.EnrollmentDate); break; default: students = students.OrderBy(s => s.LastName); break; } return View(students.ToList());}

Page 9: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

The New Index Method

• Refer to Modification 1:• Method receives “sortorder” string as input• sortorder values expected:– Name– name_desc ( name descending)– Date– date_desc ( date descending)

• Default – Last Name, ascending

Page 10: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Processing Logic

• Refer to Modification 1:• First time through:– sortorder is null– List is displayed in ascending Name order

• Entered as a result of user clicking column heading:– sortorder value will be established in the query

string created by the hyperlink – “Name”, “name_desc”, “Date”, “date_desc”)

Page 11: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Controller/View Communication

• The View simply displays the List of Students sent to it by the Controller.

• The Controller establishes the order for the Student List.

• If the user wishes to see a different order, s/he clicks on the column header.

• This will generate a subsequent query back to the controller, identifying which column has been selected and the requested ascending/descending order.

Page 12: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

The ViewBag Variables

• The ViewBag can be used to share information between the Controller and the View

• Two ViewBag variables used here:– ViewBag.NameSortParm– ViewBag.DateSortParm

• Values are set in the Controller• Values are used in the View to configure the column header

hyperlinks• The column header hyperlinks

– Identify what order the display is to be changed to – “toggle” whether the display is to be in ascending or descending

order

Page 13: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

MVC Principle

• The bulk of the processing is done by the Controller, on the data in the Model.

• The View simply displays the data in the Model.

• Controls on the View may be configured from data in the ViewBag to request actions elsewhere in the application – here, in another display from the originating controller.

Page 14: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

ViewBag Variables

• Refer to Modification 1• Ternary statements – (composed of three parts)• If sortorder parm is null or empty (implies this is the default

first time through or a name-ascending display was requested– Set the NameSortParm to “name-descending” (toggle the

LastName heading to generate a descending request if clicked)– ELSE – Set the NameSortPart to “ “ (empty string – configure the Last

Name heading to generate an ascending request if clicked)

ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

Page 15: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

The sortOrder parameter• Describes the order in which the student list will be displayed• Sets up the hyperlinks in the column headers for a subsequent user click

Current sort order Last Name Hyperlink Date Hyperlink

Last Name ascending descending ascending

Last Name descending ascending ascending

Date ascending ascending descending

Date descending ascending ascending

Page 16: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Student Activity

• Apply the highlighted code in Modification 2 to Views\Student\index.cshtml

<p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm }) </th> <th>First Name </th> <th> @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm }) </th> <th></th>

</tr>

Page 17: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Run the page

• Click the Date column header and verify that the list is in Date order

• Click the LastName column header and verify that the list is in Last Name order

Page 18: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 19: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 20: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

ADD A SEARCH TEXT BOX – LAST NAME, FIRST NAME SEARCH

Objective 2

Page 21: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Student Activity

• Apply Modification 4 to Views\Student\index.cshtml

<p> @Html.ActionLink("Create New", "Create") </p> @using (Html.BeginForm()) { <p> Find by name: @Html.TextBox("SearchString") <input type="submit" value="Search" /></p> } <table> <tr>

Page 22: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Student Activity

• Apply the entire Modification 5 to replace the index method in Controllers\StudentController.cs (changes are hightlighted)

Page 23: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Run the Student Page

• Search for ‘an’ in the first or last name

Page 24: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

CREATE A PAGING FEATURE Objective 3

Page 25: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 26: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Paging Feature Approach

• Install a NuGet Package (PagedList.MVC)• Change the Index method• Add paging links to the Index view.

Page 27: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

PagedList.Mvc – NuGet Package

• Installs a collection type and extension methods– For both

• IQueryable collections (Outside of memory – LINQ or SQL)• IEnumerable collections (In memory)

• Extension methods a single page of data in a PagedList collection

• PagedList collection provides properties and methods that facilitate paging

• A paging helper is installed that can display the paging buttons

Page 28: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT ACTIVITY

• Tools Menu | Library Package Manager | Package Manager Console

• In Console, make sure:– Package Source = nuget.org– Default Project = ContosoUniversity

• Then type

Install-Package PagedList.Mvc

Page 29: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 30: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Analysis of modified StudentController Index method

• New parameters:– page– current sort order– current filter

• All parameters null if– First time through– User hasn’t clicked sorting or paging link

• If paging link has been clicked, page parameter contains the page number to display

• Current sort order is passed to View through the ViewBag– The current sort order is required to keep the same sort order whilst paging.

public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)

ViewBag.CurrentSort = sortOrder;

Page 31: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Code analysis, continued …

• currentFilter – provides the current filter string.• If search string is changed during paging– Page must be set to 1 (different data will be displayed)

• When new search value is entered into text box and submit pressed, searchString will not be null.

if (searchString != null){ page = 1;}else{ searchString = currentFilter;}

Page 32: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Bottom of code – analysis continued …

• ToPagedList extension method passes a single page of students to the View. Page is in a collection type that supports paging.

• (page??1) – ?? null coalescing operator– Returns page if not null, else returns 1

int pageSize = 3;int pageNumber = (page ?? 1);return View(students.ToPagedList(pageNumber, pageSize));

Page 33: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT ACTIVITYModify Student Index View for Paging

• Replace all the code in Views\Student\Index.cshtml with the code in Modification 7. – Note: cut and paste all the code; it extends over

two pages

Page 34: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Code Analysis

• Please refer to code in Modification 7• @model statement – View now gets a PagedList object

instead of a List object• using – access MVC helper for paging buttons• BeginForm now specifies FormMethod.Get– Default BeginForm - parameters passed in message body

(POST)– Get recommended when action does not result in an update

– W3C– Get passes parameters in query string – user can bookmark

the URL

Page 35: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Code Analysis, continued

• Initializing the text box with the current search string allows the user to see the search string when a new page is displayed

• Header links are now passed the current filter so that the user can sort within filter results

• Current page and total number of pages are displayed

• Page 0 of 0 is displayed• Paging buttons are displayed by PageListPager

helper

Page 36: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT ACTIVITY

• Run the page• Verify paging works• Verify filtering within paging works

Page 37: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 38: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT STATISTICS PAGEObjective 4

Page 39: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 40: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

Student Statistics Page

• Displays how many students have enrolled for each enrollment date

• Involves grouping and simple group calculations

• Approach:– New model class for View– Modify About method in HomeController– Modify the About View

Page 41: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT ACTIVITY

Add a new folder to the project (ViewModels)Add a new class to this folder (EnrollmentDateGroup.cs)Replace the template code with the code in Modification 8.

using System;using System.ComponentModel.DataAnnotations;

namespace ContosoUniversity.ViewModels{ public class EnrollmentDateGroup { [DataType(DataType.Date)] public DateTime? EnrollmentDate { get; set; }

public int StudentCount { get; set; } }}

Page 42: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT ACTIVITYIn HomeController.cs:

Add the following using statements at the top of the file.

using ContosoUniversity.DAL;using ContosoUniversity.ViewModels;

Add a class variable for the database context immediately after the curly brace

public class HomeController : Controller{ private SchoolContext db = new SchoolContext();

Replace the About method in HomeController.cs with the code in Modification 9.

Add a Dispose method to HomeController.cs as shown in Modification 10.

Page 43: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

STUDENT ACTIVITY

• Replace the code in module Views\Home\About.cshtml with the code in Modification 11.

• Run the app and view the About screen.

Page 44: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins
Page 45: Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins

FINIS