Adding a model
https://docs.asp.net/en/latest/tutorials/first-mvc-app/adding-model.html
Adding data model classes
In Solution Explorer, right click the Models folder > Add > Class. Name the class Movie and add the following properties:
using System; namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; }
}
}
n addition to the properties you’d expect to model a movie, the ID field is required by the DB for the primary key.
Build the project.
If you don’t build the app, you’ll get an error in the next section.
We’ve finally added a Model to our MVC app.
Scaffolding a controller
In Solution Explorer, right-click the Controllers folder > Add > Controller.
In the Add Scaffold dialog, tap MVC Controller with views, using Entity Framework > Add.
Complete the Add Controller dialog
- Model class: Movie(MvcMovie.Models)
- Data context class: ApplicationDbContext(MvcMovie.Models)
- Views:: Keep the default of each option checked
- Controller name: Keep the default MoviesController
- Tap Add
The Visual Studio scaffolding engine creates the following:
- A movies controller (Controllers/MoviesController.cs)
- Create, Delete, Details, Edit and Index Razor view files (Views/Movies)
Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and views for you (the automatic creation of CRUD action methods and views is known as scaffolding).
You’ll soon have a fully functional web application that lets you create, list, edit, and delete movie entries.
If you run the app and click on the Mvc Movie link, you’ll get the following errors:


We’ll follow those instructions to get the database ready for our Movie app.
Update the database
Warning
You must stop IIS Express before you update the database.
To Stop IIS Express:
- Right click the IIS Express system tray icon in the notification area
- Tap Exit or Stop Site
- Alternatively, you can exit and restart Visual Studio
- Open a command prompt in the project directory (MvcMovie/src/MvcMovie). Follow these instructions for a quick way to open a folder in the project directory.
- Open a file in the root of the project (for this example, use Startup.cs.)
- Right click on Startup.cs > Open Containing Folder.
- Shift + right click a folder > Open command window here
- Run
cd ..to move back up to the project directory
- Run the following commands in the command prompt:
dotnet ef migrations add Initial
dotnet ef database update
dotnet ef commands
dotnet(.NET Core) is a cross-platform implementation of .NET. You can read about it heredotnet ef migrations add InitialRuns the Entity Framework .NET Core CLI migrations command and creates the initial migration.
The parameter “Initial” is arbitrary, but customary for the first (initial) database migration.
This operation creates the Data/Migrations/<date-time>_Initial.cs file containing the migration commands to add (or drop) the Movie table to the database
dotnet ef database updateUpdates the database with the migration we just created
Test the app
If your browser is unable to connect to the movie app you might need to wait for IIS Express to load the app.
It can sometimes take up to 30 seconds to build the app and have it ready to respond to requests.
- Run the app and tap the Mvc Movie link
- Tap the Create New link and create a movie
You may not be able to enter decimal points or commas in the Price field.
To support jQuery validation for non-English locales that use a comma (”,”) for a decimal point, and non US-English date formats, you must take steps to globalize your app.
See Additional resources for more information. For now, just enter whole numbers like 10.
In some locals you’ll need to specify the date format. See the highlighted code below.
中国这边的时间,默认识别的是年月日或者月日年,但是年份需要是4位数的,比如1989-07-12或者07-12-1989
using System;
using System.ComponentModel.DataAnnotations; namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] //输入的时候需要按照指定的格式来输入
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}
Tapping Create causes the form to be posted to the server, where the movie information is saved in a database.
You are then redirected to the /Movies URL, where you can see the newly created movie in the listing.
Create a couple more movie entries. Try the Edit, Details, and Delete links, which are all functional.
Examining the Generated Code
Open the Controllers/MoviesController.cs file and examine the generated Index method.
A portion of the movie controller with the Index method is shown below:
public class MoviesController : Controller
{
private readonly ApplicationDbContext _context; public MoviesController(ApplicationDbContext context)
{
_context = context;
} // GET: Movies
public async Task<IActionResult> Index()
{
return View(await _context.Movie.ToListAsync());
}
}
The constructor uses Dependency Injection to inject the database context into the controller.
The database context is used in each of the CRUD methods in the controller. //Create增 Read查 Update改 Delete删
A request to the Movies controller returns all the entries in the Movies table and then passes the data to the Index view.
Strongly typed models and the @model keyword
Earlier in this tutorial, you saw how a controller can pass data or objects to a view using the ViewData dictionary.
The ViewData dictionary is a dynamic object that provides a convenient late-bound way to pass information to a view.
MVC also provides the ability to pass strongly typed objects to a view.
This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in Visual Studio (VS).
The scaffolding mechanism in VS used this approach (that is, passing a strongly typed model) with the MoviesController class and views when it created the methods and views.
Examine the generated Details method in the Controllers/MoviesController.cs file:
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
} var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
if (movie == null)
{
return NotFound();
} return View(movie);
}
The id parameter is generally passed as route data, for examplehttp://localhost:1234/movies/details/1 sets:
- The controller to the
moviescontroller (the first URL segment) - The action to
details(the second URL segment) - The id to 1 (the last URL segment)
You could also pass in the id with a query string as follows:
http://localhost:1234/movies/details?id=1
If a Movie is found, an instance of the Movie model is passed to the Details view:
return View(movie);
Examine the contents of the Views/Movies/Details.cshtml file:
@model MvcMovie.Models.Movie //注意这里的model对应于下面使用的,相当于sqlserver里面存储过程声明变量的类型
@{
ViewData["Title"] = "Details";
}
<h2>Details</h2>
<div>
<h4>Movie</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Genre)
</dt>
<dd>
@Html.DisplayFor(model => model.Genre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Price)
</dt>
<dd>
@Html.DisplayFor(model => model.Price)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ReleaseDate)
</dt>
<dd>
@Html.DisplayFor(model => model.ReleaseDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
By including a @model statement at the top of the view file, you can specify the type of object that the view expects.
When you created the movie controller, Visual Studio automatically included the following @model statement at the top of the Details.cshtml file:
@model MvcMovie.Models.Movie
This @model directive allows you to access the movie that the controller passed to the view by using a Model object that’s strongly typed.
For example, in the Details.cshtml view, the code passes each movie field to the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Modelobject.
The Create and Edit methods and views also pass a Movie model object.
Examine the Index.cshtml view and the Index method in the Movies controller.
Notice how the code creates a List object when it calls the View method.
The code passes this Movies list from the Index action method to the view:
public async Task<IActionResult> Index()
{
return View(await _context.Movie.ToListAsync());
}
When you created the movies controller, Visual Studio automatically included the following @modelstatement at the top of the Index.cshtml file:
@model IEnumerable<MvcMovie.Models.Movie>
The @model directive allows you to access the list of movies that the controller passed to the view by using a Model object that’s strongly typed.
For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object:
@model IEnumerable<MvcMovie.Models.Movie>
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item in the loop is typed as Movie.
Among other benefits, this means that you get compile-time checking of the code and full IntelliSense support in the code editor:

You now have a database and pages to display, edit, update and delete data. In the next tutorial, we’ll work with the database.
Additional resources
Adding a model的更多相关文章
- 008.Adding a model to an ASP.NET Core MVC app --【在 asp.net core mvc 中添加一个model (模型)】
Adding a model to an ASP.NET Core MVC app在 asp.net core mvc 中添加一个model (模型)2017-3-30 8 分钟阅读时长 本文内容1. ...
- ASP.NET Core 中文文档 第二章 指南(4.4)添加 Model
原文:Adding a model 作者:Rick Anderson 翻译:娄宇(Lyrics) 校对:许登洋(Seay).孟帅洋(书缘).姚阿勇(Mr.Yao).夏申斌 在这一节里,你将添加一些类来 ...
- 创建ASP.NET Core MVC应用程序(4)-添加CRUD动作方法和视图
创建ASP.NET Core MVC应用程序(4)-添加CRUD动作方法和视图 创建CRUD动作方法及视图 参照VS自带的基架(Scaffold)系统-MVC Controller with view ...
- Getting Started with ASP.NET Web API 2 (C#)
By Mike Wasson|last updated May 28, 2015 7556 of 8454 people found this helpful Print Download Com ...
- 简单记录在Visual Studio 2013中创建ASP.NET Web API 2
在很多跨平台的应用中就需要Web API ,比如android与数据库的交互. Create a Web API Project 选择新建项目下的模板下的Visual C#节点下的Web节点,在模板列 ...
- ASP.NET Web API与Rest web api(一)
HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that exp ...
- ASP.NET Web API与Rest web api(一)
本文档内容大部分来源于:http://www.cnblogs.com/madyina/p/3381256.html HTTP is not just for serving up web pages. ...
- 【ASP.NET Web API教程】1.1 第一个ASP.NET Web API
Your First ASP.NET Web API (C#)第一个ASP.NET Web API(C#) By Mike Wasson|January 21, 2012作者:Mike Wasson ...
- MVC架构学习
作为一名小小的GreenBird,学习MVC呢,已经花费了2天了,期间得到了美丽的学姐的帮助,初步整理了一下. 首先,学习MVC呢就先以一个标准的MVC的简单的例子来入手,然后根据学姐的PPT,我用v ...
随机推荐
- 微信小程序特殊字符转义方法——&转义&等等
在我编写公司小程序的过程中,有一次在网页端添加了一张图片,结果在小程序端访问失败了,究其原因,竟然是因为该图片名称中有一个“&”符号,网页端添加后,自动转义成了“&”存储到了数据库.当 ...
- 自学Python六 爬虫基础必不可少的正则
要想做爬虫,不可避免的要用到正则表达式,如果是简单的字符串处理,类似于split,substring等等就足够了,可是涉及到比较复杂的匹配,当然是正则的天下,不过正则好像好烦人的样子,那么如何做呢,熟 ...
- 用DIV遮罩解决checkbox勾选无效的问题
在前端开发的过程中,遇到一种情况,需要勾选,为了用户的操作便捷就将click事件放到了DIV上.(其中使用了knockout.js) 代码大概如下: <div id="one" ...
- SQL Server 置疑、可疑、正在恢复
一.出错情况 有些时候当你重启了数据库服务,会发现有些数据库变成了正在恢复.置疑.可疑等情况,这个时候DBA就会很紧张了,下面是一些在实践中得到证明的方法. 在一次重启数据库服务后,数据库显示正在恢复 ...
- 【Oracle】详解10053事件
借助Oracle的10053事件event,我们可以监控到CBO对SQL进行成本计算和路径选择的过程和方法. 10053事件有两个级别: Level 2:2级是1级的一个子集,它包含以下内容: Col ...
- 设置Hadoop的 dataNode的单个Map的内存配置
1.进入hadoop的配置目录 ,找到 环境变量的 $HADOOP_HOME cd $HADOOP_HOME 2.修改dataNode 节点的 单个map的能使用的内存配置 找到配置的文件: /opt ...
- 如何修改yii2.0用户登录使用的user表为其它的表
这只是自己练习的一个记录而已. 因为某种原因,不想用yii自带的user表,想用自己建的admin数据库表,修改如下: 1. 参考高级模板里里的common\models\User 修改 Admi ...
- 06--c++友元类
=======================什么是友元类======================= 当一个类B成为了另外一个类A的“朋友”时,那么类A的私有和保护的数据成员就可以被类B访问.我们 ...
- 3D模型在UI上显示的方法(Unity)
方法:使用RawImage通过Render Texter将摄像机下的物体渲染纹理记录并显示在RawImage上面 具体实现:新建一个模型(Cube),新建一个摄像机,将Clear Flags设置为So ...
- 宏、预编译(day12)
指针数组里的每个存储区是一个指针类型 的存储区 字符指针数组里包含多个字符类型指针,其中 每个指针可以表示一个字符串 字符指针数组可以用来表示多个相关字符串 主函数的第二个参数是一个字符指针数组, 其 ...