- 浏览: 1068025 次
- 性别:
- 来自: 长沙
文章分类
- 全部博客 (639)
- 服务器配置篇 (58)
- hibernate篇 (14)
- spring篇 (33)
- struts篇 (28)
- JS篇 (46)
- 其他技术篇 (46)
- 数据库集群配置 (6)
- JAVA基础相关 (48)
- 分布式框架HadHoop的应用 (2)
- FLEX篇 (8)
- SQLSERVER技术 (32)
- Android学习 (13)
- amchart学习笔记 (1)
- openfire+smark搭建即时通讯 (9)
- Linux学习 (18)
- Oracle数据库 (15)
- 网站优化技术 (12)
- mysql数据库 (2)
- 项目学习总结 (18)
- 工具类(JAVA) (12)
- 工具类(JS) (2)
- 设计模式 (10)
- Lucene学习 (24)
- EJB3学习 (6)
- Sphinx搜索引擎 (3)
- 工作中用到的软件小工具 (5)
- .NET (49)
- JAVA 连接SQLSERVER2008步骤 (1)
- MongoDB (19)
- Android手机开发 (3)
- Maven (6)
- vue (9)
- Shiro (4)
- mybatis (3)
- netty框架 (1)
- SpringCloud (3)
- spring-cloud (7)
- Git (1)
- dubbo (2)
- springboot (13)
- rocketmq (1)
- git学习 (2)
- kafka服务器 (2)
- linux (10)
- WEB系统辅助项目 (1)
- jenkins (2)
- docker (4)
- influxdb (3)
- python (2)
- nginx (1)
最新评论
-
jiangfuofu555:
这样数据量大,效率怎么样?
sqlserver 实现分页的前台代码 以及后台的sqlserver语句 -
w156445045:
博主请问下,如何做到实时的刷新呢,
另外我后台是Java 谢谢 ...
web 版本的汽车仪表盘,非常好看。还有各种图形 -
jackyin5918:
<transportConnector name=&qu ...
ActiveMQ的activemq.xml详细配置讲解 -
握着橄榄枝的人:
你这个不是spring1.x的吧
spring1.x使用AOP实例 -
xiaophai:
全乱套了!
openfire+spark搭建完美的及时通讯
In the previous tutorial you implemented a set of web pages for basic CRUD operations for Student
entities. In this tutorial you'll add sorting, filtering, and paging functionality to the Students
Index page. You'll also create a page that does simple grouping.
The following illustration shows what the page will look like when you're done. The column headings are links that the user can click to sort by that column. Clicking a column heading repeatedly toggles between ascending and descending sort order.
Adding Column Sort Links to the Students Index Page
To add sorting to the Student Index page, you'll change the Index
method of the Student
controller and add code to the Student Index view.
Adding Sorting Functionality to the Index Method
In Controllers\StudentController.cs, replace the Index
method with the following code:
public ViewResult 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()); }
This code receives a sortOrder
parameter from the query string in the URL, which is provided by ASP.NET MVC as a parameter to the action method. The parameter will be a string that's either "Name" or "Date", optionally followed by a space and the string "desc" to specify descending order.
The first time the Index page is requested, there's no query string. The students are displayed in ascending order by LastName
, which is the default as established by the fall-through case in the switch
statement. When the user clicks a column heading hyperlink, the appropriate sortOrder
value is provided in the query string.
The two ViewBag
variables are used so that the view can configure the column heading hyperlinks with the appropriate query string values:
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date";
These are ternary statements. The first one specifies that if the sortOrder
parameter is null or empty, ViewBag.NameSortParm
should be set to "Name desc"; otherwise, it should be set to an empty string.
There are four possibilities, depending on how the data is currently sorted:
- If the current order is Last Name ascending, the Last Name link must specify Last Name descending, and the Enrollment Date link must specify Date ascending.
- If the current order is Last Name descending, the links must indicate Last Name ascending (that is, empty string) and Date ascending.
- If the current order is Date ascending, the links must indicate Last Name ascending and Date descending.
- If the current order is Date descending, the links must indicate Last Name ascending and Date ascending.
The method uses LINQ to Entities to specify the column to sort by. The code creates an IQueryable
variable before the switch
statement, modifies it in the switch
statement, and calls the ToList
method after the switch
statement. When you create and modify IQueryable
variables, no query is sent to the database. The query is not executed until you convert the IQueryable
object into a collection by calling a method such as ToList
. Therefore, this code results in a single query that is not executed until the return View
statement.
Adding Column Heading Hyperlinks to the Student Index View
In Views\Student\Index.cshtml, replace the <tr>
and <th>
elements for the heading row with the following code:
<tr> <th></th> <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> </tr>
This code uses the information in the ViewBag
properties to set up hyperlinks with the appropriate query string values.
Run the page and click the column headings to verify that sorting works.
Adding a Search Box to the Students Index Page
To add filtering to the Student Index page, you'll add a text box and a submit button to the view and make corresponding changes in the Index
method. The text box will let you enter a string to search for in the first name and last name fields.
Adding Filtering Functionality to the Index Method
In Controllers\StudentController.cs, replace the Index
method with the following code:
public ViewResult Index(string sortOrder, string searchString) { ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date"; var students = from s in db.Students select s; if (!String.IsNullOrEmpty(searchString)) { students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper()) || s.FirstMidName.ToUpper().Contains(searchString.ToUpper())); } 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()); }
You've added a searchString
parameter to the Index
method. You've also added a where
clause to the LINQ statement that selects only students whose first name or last name contains the search string. The search string value is received from a text box that you'll add later to the Index view. The statement that adds the where
clause is executed only if there's a value to search for:
if (!String.IsNullOrEmpty(searchString)) { students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper()) || s.FirstMidName.ToUpper().Contains(searchString.ToUpper())); }
Note The .NET Framework implementation of the Contains
method returns all rows when you pass an empty string to it, but the Entity Framework provider for SQL Server Compact 4.0 returns zero rows for empty strings. Therefore the code in the example (putting the Where
statement inside an if
statement) makes sure that you get the same results for all versions of SQL Server. Also, the .NET Framework implementation of the Contains
method performs a case-sensitive comparison by default, but Entity Framework SQL Server providers perform case-insensitive comparisons by default. Therefore, calling the ToUpper
method to make the test explicitly case-insensitive ensures that results do not change when you change the code later to use a repository, which will return an IEnumerable
collection instead of an IQueryable
object. (When you call the Contains
method on an IEnumerable
collection, you get the .NET Framework implementation; when you call it on an IQueryable
object, you get the database provider implementation.)
Adding a Search Box to the Student Index View
In Views\Student\Index.cshtml, add a caption, a text box, and a Search button immediately before the opening table
tag:
@using (Html.BeginForm()) { <p> Find by name: @Html.TextBox("SearchString") <input type="submit" value="Search" /></p> }
Run the page, enter a search string, and click Search to verify that filtering is working.
Adding Paging to the Students Index Page
To add paging to the Student Index page, you'll start by installing the PagedList NuGet package. Then you'll make additional changes in the Index
method and add paging links to the Index
view. The following illustration shows the paging links.
Installing the PagedList NuGet Package
The NuGet PagedList package installs a PagedList
collection type. When you put query results in a PagedList
collection, several properties and methods are provided that facilitate paging.
In Visual Studio, make sure the project (not the solution) is selected. From the Tools menu, select Library Package Manager and then Add Library Package Reference.
In the Add Library Package Reference dialog box, click the Online tab on the left and then enter "pagedlist" in the search box. When you see the PagedList package, click Install.
Adding Paging Functionality to the Index Method
In Controllers\StudentController.cs, add a using
statement for the PagedList
namespace:
using PagedList;
Replace the Index
method with the following code:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page) { ViewBag.CurrentSort = sortOrder; ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date"; if (Request.HttpMethod == "GET") { searchString = currentFilter; } else { page = 1; } ViewBag.CurrentFilter = searchString; var students = from s in db.Students select s; if (!String.IsNullOrEmpty(searchString)) { students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper()) || s.FirstMidName.ToUpper().Contains(searchString.ToUpper())); } 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; } int pageSize = 3; int pageIndex = (page ?? 1) - 1; return View(students.ToPagedList(pageIndex, pageSize)); }
This code adds a page
parameter, a current sort order parameter, and a current filter parameter to the method signature, as shown here:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
The first time the page is displayed, or if the user hasn't clicked a paging link, the page
variable is null. If a paging link is clicked, the page
variable will contain the page number to display.
A ViewBag
property provides the view with the current sort order, because this must be included in the paging links in order to keep the sort order the same while paging:
ViewBag.CurrentSort = sortOrder;
Another ViewBag
property provides the view with the current filter string, because this string must be restored to the text box when the page is redisplayed. In addition, the string must be included in the paging links in order to maintain the filter settings during paging. Finally, if the search string is changed during paging, the page has to be reset to 1, because the new filter can result in different data to display, hence the original page might not even exist anymore.
if (Request.HttpMethod == "GET") { searchString = currentFilter; } else { page = 1; } ViewBag.CurrentFilter = searchString;
At the end of the method, the student query is converted to a PagedList
instead of to a List
so that it will be passed to the view in a collection that supports paging. This is the code:
int pageSize = 3; int pageIndex = (page ?? 1) - 1; return View(students.ToPagedList(pageIndex, pageSize));
The ToPagedList
method takes a page index value, which is zero-based, rather than a page number, which is one-based. Therefore, the code subtracts 1 from the page number in order to get the page index. (The two question marks represent an operator that defines a default value for a nullable type; the expression (page ?? 1)
means return the value of page
if it has a value, or return 1 if page
is null. In other words, set pageIndex
to page - 1
if page
is not null, or set it to 1 - 1
if page
is null.)
Adding Paging Links to the Student Index View
In Views\Student\Index.cshtml, replace the existing code with the following code:
@model PagedList.IPagedList<ContosoUniversity.Models.Student> @{ ViewBag.Title = "Students"; } <h2>Students</h2> <p> @Html.ActionLink("Create New", "Create") </p> @using (Html.BeginForm()) { <p> Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string) <input type="submit" value="Search" /></p> } <table> <tr> <th></th> <th> @Html.ActionLink("Last Name", "Index", new { sortOrder=ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter }) </th> <th> First Name </th> <th> @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter }) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) | @Html.ActionLink("Details", "Details", new { id=item.StudentID }) | @Html.ActionLink("Delete", "Delete", new { id=item.StudentID }) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.FirstMidName) </td> <td> @Html.DisplayFor(modelItem => item.EnrollmentDate) </td> </tr> } </table> <div> Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount @if (Model.HasPreviousPage) { @Html.ActionLink("<<", "Index", new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter }) @Html.Raw(" "); @Html.ActionLink("< Prev", "Index", new { page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter }) } else { @:<< @Html.Raw(" "); @:< Prev } @if (Model.HasNextPage) { @Html.ActionLink("Next >", "Index", new { page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter }) @Html.Raw(" "); @Html.ActionLink(">>", "Index", new { page = Model.PageCount, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter }) } else { @:Next > @Html.Raw(" ") @:>> } </div>
The @model
statement at the top of the page specifies that the view now gets a PagedList
object instead of a List
object.
The text box is initialized with the current search string so that the user can page through filter results without the search string disappearing:
Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
The column header links use the query string to pass the current search string to the controller so that the user can sort within filter results:
@Html.ActionLink("Last Name", "Index", new { sortOrder=ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter })
On one line at the bottom of the page, this code displays the following navigation UI:
Page [current page number] of [total number of pages] << < Prev Next > >>
The <<
symbol is a link to the first page, < Prev is a link to the previous page, and so on. If the user is currently on page 1, the links to move backward are disabled; similarly, if the user is on the last page, the links to move forward are disabled. Each paging link passes the new page number and the current sort order and search string to the controller in the query string. This lets you maintain the sort order and filter results during paging.
If there are no pages to display, "Page 0 of 0" is shown. (In that case the page number is greater than the page count because Model.PageNumber
is 1, and Model.PageCount
is 0.)
Run the page.
Click the paging links in different sort orders to make sure paging works. Then enter a search string and try paging again to verify that paging also works correctly with sorting and filtering.
Creating an About Page That Shows Student Statistics
For the Contoso University website's About page, you'll display how many students have enrolled for each enrollment date. This requires grouping and simple calculations on the groups. To accomplish this, you'll do the following:
- Create a view model class for the data that you need to pass to the view.
- Modify the
About
method in theHome
controller. - Modify the
About
view.
Creating the View Model
Create a ViewModels folder. In that folder, create EnrollmentDateGroup.cs and replace the existing code with the following code:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ContosoUniversity.ViewModels { public class EnrollmentDateGroup { [DisplayFormat(DataFormatString = "{0:d}")] public DateTime? EnrollmentDate { get; set; } public int StudentCount { get; set; } } }
Modifying the Home Controller
In HomeController.cs, add the following using
statements:
using ContosoUniversity.DAL; using ContosoUniversity.Models; using ContosoUniversity.ViewModels;
Add a class variable for the database context:
private SchoolContext db = new SchoolContext();
Replace the About
method with the following code:
public ActionResult About() { var data = from student in db.Students group student by student.EnrollmentDate into dateGroup select new EnrollmentDateGroup() { EnrollmentDate = dateGroup.Key, StudentCount = dateGroup.Count() }; return View(data); }
The LINQ statement groups the student entities by enrollment date, calculates the number of entities in each group, and stores the results in a collection of EnrollmentDateGroup
view model objects.
Modifying the About View
Replace the code in the Views\Home\About.cshtml file with the following code:
@model IEnumerable<ContosoUniversity.ViewModels.EnrollmentDateGroup> @{ ViewBag.Title = "Student Body Statistics"; } <h2>Student Body Statistics</h2> <table> <tr> <th> Enrollment Date </th> <th> Students </th> </tr> @foreach (var item in Model) { <tr> <td> @String.Format("{0:d}", item.EnrollmentDate) </td> <td> @item.StudentCount </td> </tr> } </table>
Run the page. The count of students for each enrollment date is displayed in a table.
You've now seen how to create a data model and implement basic CRUD, sorting, filtering, paging, and grouping functionality. In the next tutorial you'll begin looking at more advanced topics by expanding the data model.
Links to other Entity Framework resources can be found at the end of the last tutorial in this series.
发表评论
-
C# WinForm程序如何与js交互
2012-07-15 22:28 2318一、建立网页 <html ... -
SQLITE FOR .NET4.0使用说明以及DLL
2012-06-28 22:07 1203SQLITE FOR .NET4.0使用说明以及DLL -
WinForm中TabControl的一些事件写法(C#)
2012-06-27 20:41 9878在TabControl控件中并没提供单个选项卡的Click事件 ... -
C# 通过字符串动态创建一个窗体
2012-06-27 20:27 1745private void button1_Click(obje ... -
vs2010 打包winform成EXE文件
2012-04-20 14:03 1645见附件 -
C#中DataGridView控件60招
2012-01-13 09:36 65571. DataGridView当前的单元格属性取得、变更 2 ... -
单击dataGridView某一行时将dataGridView当前选择行的某列值赋值给某个文本框
2012-01-13 09:19 2460SelectedRows和CurrentRow之间的区别 ... -
c# winform开发-datagridview开发
2012-01-13 09:18 1728datagridview 操作详解 目录: 1、 取得或 ... -
C# 中奇妙的函数. String Split 和 Join
2011-10-25 10:51 1111很多时候处理字符串数据,比如从文件中读取或者存入 - 我们可能 ... -
asp.net中web.config配置节点大全详解
2011-10-25 10:16 1374asp.net中web.config配置节点大全详解 2 ... -
Entity Framework in ASP.NET MVC Application (二)
2011-05-10 20:29 1699In the previous tutorial you cr ... -
Entity Frame Work 4.1调用存储过程
2011-05-10 20:24 2134在这个问题上,琢磨了很久了。今天终于找到了调用的方法。 存储 ... -
entity-framework (code-first)实例开发(一)
2011-05-09 20:40 2752The Contoso University Web Appl ... -
使用ef4.1 的dbcontext进行数据库循环操作
2011-04-24 23:06 2264如果你想要调用一个类的方法进行循环操作:官方的例子: Dis ... -
使用EF 4.1的DbContext
2011-04-24 22:36 3642简述:EF4.1包括Code First和DbContext ... -
ADO.NET 访问存储过程
2011-04-24 22:15 1591ADO.NET 访问存储过程其实也比较简单,但是有些小细节部分 ... -
JAVA与.NET的相互调用——通过Web服务实现相互调用(附原代码)
2011-04-24 20:58 1287JAVA与.NET是现今世界竞争激烈的两大开发媒体,两者语言有 ... -
视图模式/视图->视图包
2011-04-24 20:16 1472ASP.NET MVC(自V1起)就支持一个带控制器和视图的V ... -
SkipRequestValidation] –> [AllowHtml]
2011-04-24 20:15 1437ASP.NET MVC内置了防止HTML和跨站脚本注入攻击的支 ... -
Log4net 详细说明
2011-04-12 22:29 2071在实际项目中我们经常 ...
相关推荐
1. **项目初始化**:创建一个新的ASP.NET MVC项目,并在项目中引入Entity Framework库。 2. **定义模型**:创建表示数据库实体的C#类。这些类包含属性,对应于数据库表的列。例如,一个`Student`类可能包含`Id`、`...
**ASP.NET MVC 应用程序与 Entity Framework** ASP.NET MVC(Model-View-Controller)是一种广泛使用的开源Web应用程序框架,由Microsoft开发。它基于模式驱动的设计,鼓励清晰的分离关注点,使开发者能够构建可...
Model, map, and access data effectively with Entity Framework Core 2, ...This book is for ASP.NET Core MVC 2 developers who want to use Entity Framework Core 2 as the data access layer in their projects.
在本项目中,数据访问层可能通过ADO.NET或者Entity Framework与数据库交互,获取或保存商品信息。 5. **数据库实现**:项目可能使用SQL Server或其他关系型数据库存储商品信息。数据库设计应遵循规范化原则,确保...
- 在Visual Studio 2008中,选择"文件" > "新建项目",然后选择"ASP.NET MVC Web Application"模板。 - 输入项目名称,例如"TaskList",然后确认创建。 - 如果出现创建单元测试项目的提示,可根据需求选择是否...
在本文中,我们将深入探讨如何使用AngularJS、ASP.NET MVC、Web API和Entity Framework(EF)构建一个完整的多层Single Page Application(SPA)。这个技术栈是现代Web开发中常用的一组工具,它们协同工作,可以提供...
ASP.NET MVC4与SQLite是一个强大的组合,用于构建高效、轻量级的Web应用程序。ASP.NET MVC4是一个基于模型-视图-控制器(MVC)设计模式的开源框架,它允许开发者构建可维护、可测试的Web应用。SQLite则是一个便携式...
本文将详细讲解如何利用.NET WPF(Windows Presentation Foundation)和ASP.NET MVC4技术构建一个夜猫商务会所的运营管理平台,提供一体化的解决方案。.NET WPF是微软开发的用于构建桌面应用程序的强大框架,而ASP...
You would also learn the fundamentals of Entity framework and on how to use the same in ASP.NET Core web applications. The book presents the fundamentals and philosophies of ASP.NET Core. Starting ...
开发者通常会使用ADO.NET Entity Framework或NHibernate这样的ORM(对象关系映射)工具进行数据访问。 通过这个示例源码,你可以学习到如何在ASP.NET MVC中创建控制器、视图和模型,理解路由机制,掌握如何与数据库...
在ASP.NET MVC中,我们通常使用T4模板来生成Entity Framework或其他ORM(对象关系映射)工具的数据访问层代码。这涉及到连接到数据库,创建模型类,以及生成用于CRUD操作的方法。 以下是如何使用T4模板连接到数据库...
5. **文件结构**:在提供的"MvcApplication10"项目中,我们可以看到典型的ASP.NET MVC项目结构,包括Controllers、Models、Views、App_Start、Content(存放CSS文件)、Scripts(存放JavaScript文件)等目录。...
在ASP.NET MVC中,这通常通过使用Entity Framework或ADO.NET来完成。创建一个Repository或者Service层,封装对数据库的操作,例如查询、分页等。假设我们有一个名为`Student`的数据模型,我们可以创建一个服务方法来...
【标题】"Web服务 ASP.NET MVC" 涉及的核心技术是ASP.NET框架下的MVC(Model-View-Controller)模式以及Web服务的创建。ASP.NET MVC是一个开源的Web应用程序框架,由微软开发,用于构建可测试、高性能的Web应用程序...
并内置于Visual Studio 2012,新版本ASP.NET MVC版本新增了手机模版、单页应用程序,Web API等模版,更新了一些 javascript 库,其中示例页面也使用了jquery的AJAX登录,并增加了OAuth认证/Entity Framework5的支持...