运用模型绑定和web窗体显示和检索数据(Retrieving and displaying data with model binding and web forms)
原文 http://www.asp.net/web-forms/overview/presenting-and-managing-data/model-binding/retrieving-data
此文是我翻译的中午版本。
在本教程中,你将
- 创建数据对象反应大学生注册课程
- 从对象中创建数据库表
- 用测试数据填充数据库
- 在web 窗体显示数据
Set up project
In Visual Studio 2013, 新建 ASP.NET Web Application 称作ContosoUniversityModelBinding.

选择 Web Forms 模板, 点确定创建项目。

First, you will做一些小的改动去改变你网站的面貌. 打开 Site.Master 文件, 改变标题为 Contoso University 代替原来的
<title><%: Page.Title %> - Contoso University</title>
Then, change the header text from Application name to Contoso University. <div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" runat="server" href="~/">Contoso University</a>
</div>
Also in Site.Master, change the navigation links that appear in the header to reflect the pages that are relevant to this site. You will not need either the About page or the Contact page so those links can be removed. Instead, you will need a link to a page called Students. This page has not been created yet.
<ul class="nav navbar-nav">
<li><a runat="server" href="~/">Home</a></li>
<li><a runat="server" href="~/Students">Students</a></li>
</ul>
Save and close Site.Master.
Now, you’ll create the web form for displaying student data. Right-click your project, and Add a New Item. Select the Web Form with Master Page template, and name it Students.aspx.

Select Site.Master as the master page for the new web form.
Create the data models and database
You will use Code First Migrations to create objects and the corresponding database tables. These tables will store information about the students and their courses.
In the Models folder, add a new class named UniversityModels.cs.

In this file, define the SchoolContext, Student, Enrollment, and Course classes as follows:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations; namespace ContosoUniversityModelBinding.Models
{
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
} public class Student
{
[Key, Display(Name = "ID")]
[ScaffoldColumn(false)]
public int StudentID { get; set; } [Required, StringLength(), Display(Name="Last Name")]
public string LastName { get; set; } [Required, StringLength(), Display(Name = "First Name")]
public string FirstName { get; set; } [EnumDataType(typeof(AcademicYear)), Display(Name = "Academic Year")]
public AcademicYear Year { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; }
} public class Enrollment
{
[Key]
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public decimal? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
} public class Course
{
[Key]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
} public enum AcademicYear
{
Freshman,
Sophomore,
Junior,
Senior
}
}
The SchoolContext class derives from DbContext, which manages the database connection and changes in the data.
In the Student class, notice the attributes that have been applied to the FirstName, LastName, and Yearproperties. These attributes will be used for data validation in this tutorial. To simplify the code for this demonstration project, only these properties were marked with data-validation attributes. In a real project, you would apply validation attributes to all properties that need validated data, such as properties in the Enrollment and Course classes.
Save UniversityModels.cs.
You will use the tools for Code First Migrations to set up a database based on these classes.
In Package Manager Console, run the command:enable-migrations -ContextTypeName ContosoUniversityModelBinding.Models.SchoolContext
If the command completes successfully you will receive a message stating migrations have been enabled,

Notice that a new file named Configuration.cs has been created. In Visual Studio, this file is automatically opened after it is created. The Configuration class contains a Seed method which enables you to pre-populate the database tables with test data.
Add the following code to the Seed method. You’ll need to add a using statement for theContosoUniversityModelBinding.Models namespace.
namespace ContosoUniversityModelBinding.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using ContosoUniversityModelBinding.Models; internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
} protected override void Seed(SchoolContext context)
{ context.Students.AddOrUpdate(
new Student {
FirstName = "Carson",
LastName = "Alexander",
Year = AcademicYear.Freshman },
new Student {
FirstName = "Meredith",
LastName = "Alonso",
Year = AcademicYear.Freshman },
new Student {
FirstName = "Arturo",
LastName = "Anand",
Year = AcademicYear.Sophomore },
new Student {
FirstName = "Gytis",
LastName = "Barzdukas",
Year = AcademicYear.Sophomore },
new Student {
FirstName = "Yan",
LastName = "Li",
Year = AcademicYear.Junior },
new Student {
FirstName = "Peggy",
LastName = "Justice",
Year = AcademicYear.Junior },
new Student {
FirstName = "Laura",
LastName = "Norman",
Year = AcademicYear.Senior },
new Student {
FirstName = "Nino",
LastName = "Olivetto",
Year = AcademicYear.Senior }
); context.SaveChanges(); context.Courses.AddOrUpdate(
new Course { Title = "Chemistry", Credits = },
new Course { Title = "Microeconomics", Credits = },
new Course { Title = "Macroeconomics", Credits = },
new Course { Title = "Calculus", Credits = },
new Course { Title = "Trigonometry", Credits = },
new Course { Title = "Composition", Credits = },
new Course { Title = "Literature", Credits = }
); context.SaveChanges(); context.Enrollments.AddOrUpdate(newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=},newEnrollment{StudentID=,CourseID=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=,Grade=},newEnrollment{StudentID=,CourseID=},newEnrollment{StudentID=,CourseID=,Grade=}); context.SaveChanges();}}}
Save Configuration.cs.
In the Package Manager Console, run the command add-migration initial.
Then, run the command update-database.
If you receive an exception when running this command, it is possible that the values for StudentID and CourseID have varied from the values in the Seed method. Open those tables in the database and find existing values for StudentID and CourseID. Add those values in the code for seeding the Enrollments table.
The database file has been added, but it is currently hidden in the project. Click Show All Files to display the file.

Notice the .mdf file now appears in the App_Data folder.

Double-click the .mdf file and open the Server Explorer. The tables now exist and are populated with data.

Display data from Students and related tables
With data in the database, you are now ready to retrieve that data and display it in a web page. You will use aGridView control to display the data in columns and rows.
Open Students.aspx, and locate the MainContent placeholder. Within that placeholder, add a GridView control that includes the following code.
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView runat="server" ID="studentsGrid"
ItemType="ContosoUniversityModelBinding.Models.Student" DataKeyNames="StudentID"
SelectMethod="studentsGrid_GetData"
AutoGenerateColumns="false">
<Columns>
<asp:DynamicField DataField="StudentID" />
<asp:DynamicField DataField="LastName" />
<asp:DynamicField DataField="FirstName" />
<asp:DynamicField DataField="Year" />
<asp:TemplateField HeaderText="Total Credits">
<ItemTemplate>
<asp:Label Text="<%# Item.Enrollments.Sum(en => en.Course.Credits) %>"
runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>
There are a couple of important concepts in this markup code for you to notice. First, notice that a value is set for the SelectMethod property in the GridView element. This value specifies the name of the method that is used for retrieving data for the GridView. You will create this method in the next step. Second, notice that the ItemTypeproperty is set to the Student class that you created earlier. By setting this value, you can refer to properties of that class in the markup code. For example, the Student class contains a collection named Enrollments. You can useItem.Enrollments to retrieve that collection and then use LINQ syntax to retrieve the sum of enrolled credits for each student.
In the code-behind file, you need to add the method that is specified for the SelectMethod value. OpenStudents.aspx.cs, and add using statements for the ContosoUniversityModelBinding.Models andSystem.Data.Entity namespaces.
using ContosoUniversityModelBinding.Models;
using System.Data.Entity;
Then, add the following method. Notice that the name of this method matches the name you provided for SelectMethod. public IQueryable<Student> studentsGrid_GetData()
{
SchoolContext db = new SchoolContext();
var query = db.Students.Include(s => s.Enrollments.Select(e => e.Course));
return query;
}
The Include clause improves the performance of this query but is not essential for the query to work. Without the Include clause, the data would be retrieved using lazy loading, which involves sending a separate query to the database each time related data is retrieved. By providing the Include clause, the data is retrieved using eager loading, which means all of the related data is retrieved through a single query of the database. In cases where most of the related data is not be used, eager loading can be less efficient because more data is retrieved. However, in this case, eager loading provides the best performance because the related data is displayed for each record.
For more information about performance consideration when loading related data, see the section titled Lazy, Eager, and Explicit Loading of Related Data in the Reading Related Data with the Entity Framework in an ASP.NET MVC Application topic.
By default, the data is sorted by the values of the property marked as the key. You can add an OrderBy clause to specify a different value for sorting. In this example, the default StudentID property is used for sorting. In theSorting, Paging, and Filtering Data topic, you will enable the user to select a column for sorting.
Run your web application, and navigate to the Students page. The Students page displays the following student information.

Automatic generation of model binding methods
When working through this tutorial series, you can simply copy the code from the tutorial to your project. However, one disadvantage of this approach is that you may not become aware of the feature provided by Visual Studio to automatically generate code for model binding methods. When working on your own projects, automatic code generation can save you time and help you gain a sense of how to implement an operation. This section describes the automatic code generation feature. This section is only informational and does not contain any code you need to implement in your project.
When setting a value for the SelectMethod, UpdateMethod, InsertMethod, or DeleteMethod properties in the markup code, you can select the Create New Method option.

Visual Studio not only creates a method in the code-behind with the proper signature, but also generates implementation code to assist you with performing the operation. If you first set the ItemType property before using the automatic code generation feature, the generated code will use that type for the operations. For example, when setting the UpdateMethod property, the following code is automatically generated:
// The id parameter name should match the DataKeyNames value set on the control
public void studentsGrid_UpdateItem(int id)
{
ContosoUniversityModelBinding.Models.Student item = null;
// Load the item here, e.g. item = MyDataLayer.Find(id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
return;
}
TryUpdateModel(item);
if (ModelState.IsValid)
{
// Save changes here, e.g. MyDataLayer.SaveChanges(); }
}
Again, the above code does not need to be added to your project. In the next tutorial, you will implement methods for updating, deleting and adding new data.
Conclusion
In this tutorial, you created data model classes and generated a database from those classes. You filled the database tables with test data. You used model binding to retrieve data from the database, and then displayed the data in a GridView.
In the next tutorial in this series, you will enable updating, deleting, and creating data.
运用模型绑定和web窗体显示和检索数据(Retrieving and displaying data with model binding and web forms)的更多相关文章
- ASP.NET MVC5 学习系列之模型绑定
一.理解 Model Binding Model Binding(模型绑定) 是 HTTP 请求和 Action 方法之间的桥梁,它根据 Action 方法中的 Model 类型创建 .NET 对象, ...
- 值提供器 AND 模型绑定器
本章介绍了值提供器的作用,ASP MVC自带的5中值提供器.以及模型绑定器的作用,自定义模型绑定器并使用自定义的模型绑定器(类型上加上[ModelBinder(typeof(xx))]或者在全局模型绑 ...
- WPF C# 多屏情况下,实现窗体显示到指定的屏幕内
原文:WPF C# 多屏情况下,实现窗体显示到指定的屏幕内 针对于一个程序,需要在两个显示屏上显示不同的窗体,(亦或N个显示屏N个窗体),可以使用如下的方式实现. 主要涉及到的:System.Wind ...
- [置顶]
Xamarin android 调用Web Api(ListView使用远程数据)
xamarin android如何调用sqlserver 数据库呢(或者其他的),很多新手都会有这个疑问.xamarin android调用远程数据主要有两种方式: 在Android中保存数据或调用数 ...
- 细说 Web API参数绑定和模型绑定
今天跟大家分享下在Asp.NET Web API中Controller是如何解析从客户端传递过来的数据,然后赋值给Controller的参数的,也就是参数绑定和模型绑定. Web API参数绑定就是简 ...
- 《ASP.NET MVC4 WEB编程》学习笔记------Model模型绑定
本文转载自haiziguo Asp.net mvc中的模型绑定,或许大家经常用,但是具体说他是怎么一回事,可能还是会有些陌生,那么,本文就带你理解模型绑定.为了理解模型绑定,本文会先给出其定义,然后对 ...
- 【ASP.NET Web API教程】6 格式化与模型绑定
原文:[ASP.NET Web API教程]6 格式化与模型绑定 6 Formats and Model Binding 6 格式化与模型绑定 本文引自:http://www.asp.net/web- ...
- asp.net core系列 45 Web应用 模型绑定和验证
一. 模型绑定 ASP.NET Core MVC 中的模型绑定,是将 HTTP 请求中的数据映射到action方法参数. 这些参数可能是简单类型的参数,如字符串.整数或浮点数,也可能是复杂类型的参数. ...
- .NET Core WEB API中接口参数的模型绑定的理解
在.NET Core WEB API中参数的模型绑定方式有以下表格中的几种: 微软官方文档说明地址:https://docs.microsoft.com/zh-cn/aspnet/core/web-a ...
随机推荐
- 信息收集1:DNSEUM命令
1,背景 今天无意中发现了dnsenum这个工具,在网上搜了下关于dnsenum的介绍和安装使用方法,资料不是很全,但还好这个工具也算简单,网上也都有源码,可以自行下载下来阅读阅读.本人好奇在本机(u ...
- Faster R-CNN论文详解 - CSDN博客
废话不多说,上车吧,少年 paper链接:Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks ...
- centos shell编程3【告警系统】 没有服务器端和客户端的概念 main.sh mon.conf load.sh 502.sh mail.php mail.sh disk.sh 第三十七节课
centos shell编程3[告警系统] 没有服务器端和客户端的概念 main.sh mon.conf load.sh 502.sh mail.php mail.sh disk.sh 第三十七 ...
- java模拟网页http-url访问
package com.iflytek; import java.io.InputStream; import java.net.HttpURLConnection; import java.net. ...
- Spark ListenerBus 和 MetricsSystem 体系分析
转载自:https://yq.aliyun.com/articles/60196 摘要: Spark 事件体系的中枢是ListenerBus,由该类接受Event并且分发给各个Listener.Met ...
- 使用Github发布自己的网站
1.编写好自己的index.html 2.在github上新建一个分支,分支名需要按xxx.github.com(xxx为github账号名): 3.进入分支的setting界面,自动生成网页,会在分 ...
- 获取用户真实Ip地址
REMOTE_ADDR 是你的客户端跟你的服务器“握手”时候的IP.如果使用了“匿名代理”,REMOTE_ADDR将显示代理服务器的IP.HTTP_CLIENT_IP 是代理服务器发送的HTTP头.如 ...
- EditPlus 4.3.2463 中文版已经发布(10月16日更新)
距离上个版本在本年5月发布后,EditPlus 网站沉寂多月.日前终于发布了一个新的小版本. 该版本却具有多项改进,值得一提: * Ctrl+Alt+Up/Down 键在列选模式下可插入多个插入点. ...
- navicat中文破解版,navicat破解版,navicat for mysql10.0.11简体中文破解版
https://blog.csdn.net/weixin_40426638/article/details/78933585 下载链接如下(里面有破解码) https://pan.baidu.com/ ...
- Core Java 5
p273~p276: 1.获取异常的更多信息:e.getMessage(). 2.得到异常的实际类型:e.getClass().getName(). 3.当异常之间不存在子类关系,并且异常的处理机制( ...