ASP.NET MVC 模型

本章我们将学习如何在 ASP.NET MVC 开发模式下添加数据模型

MVC 模型

MVC 模型 包含了除纯视图和控制器逻辑以外的其它所有应用程序逻辑(业务逻辑、验证逻辑、数据访问逻辑)

通过 MVC,模型可以控制并操作应用程序数据

Models 文件夹

Models 文件夹 包含表示应用程序模型的类

添加数据模型

现在,我们来添加一个数据模型

  1. 在 Solution Explorer 窗口中,右击 Models 文件夹,并选择 Add 和 Class

  2. 将类命名为 MovieDB.cs ,然后点击 Add

  3. 编辑这个类

    using System;
    using System.Collections.Generic;
    using System.Runtime.Remoting.Contexts;
    
    namespace myApp.Models
    {
        public class MovieDB
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public string Director { get; set; }
            public DateTime Date { get; set; }
        }
    
        public class MovieDBContext : Context
        {
            public ISet<MovieDB> Movies { get; set; }
        }
    }
    

    我们特意把模型命名为 "MovieDB"

    在上一章中,我们已经看到用于数据库表的 "MovieDBs"(以 s 结尾)

    这看起来有点奇怪

    不过这种命名惯例能确保模型连接上数据库表

    你必须这么使用

添加数据库控制器

接着我们再添加一个 MovieDB 的数控制器

  1. 重建您的项目:选择 生成 ,然后从菜单中选择 重新生成 myApp

  2. 在 Solution Explorer(解决方案资源管理器)中,右击 Controllers 文件夹,选择 Add 和 Controller

  3. 选择模板: Controller with read/write actions and views, using Entity Framework

  4. 选择模型类: MovieDB (myApp.Models)

  5. 选择 data context 类 MovieDBContext (myApp.Models)

  6. 设置控制器名称为 MoviesController

  7. 选择视图 Razor (CSHTML)

  8. 点击 Add

Visual Studio 将创建以下文件

  1. Controllers 文件夹中的 MoviesController.cs 文件
  2. Views 文件夹中的 Movies 文件夹

添加数据库视图

在 Movies 文件夹中,会自动创建以下文件

  1. Create.cshtml
  2. Delete.cshtml
  3. Details.cshtml
  4. Edit.cshtml
  5. Index.cshtml

恭喜

恭喜你

你已经向应用程序添加了你的第一个 MVC 数据模型

现在你可以点击 "Movies" 标签页了

ASP.NET 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

♥   简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.