理解ASP.NET中MVC 编程模型 第3章 数据模型

MVC 模型

MVC 模型包含所有应用程序逻辑(业务逻辑、验证逻辑、数据访问逻辑),除了纯视图和控制器逻辑。通过 MVC,模型可保存并操作应用程序数据。

Models 文件夹

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

以登录验证为例,创建一个 AccountModels.cs 文件,用于应用程序安全的模型。

AccountModels 包含 LogOnModelChangePasswordModel 以及 RegisterModel

LogOnModel:

public class LogOnModel

{



[Required]

[Display(Name = "User name")]

public string UserName { get; set; }



[Required]

[DataType(DataType.Password)]

[Display(Name = "Password")]

public string Password { get; set; }



[Display(Name = "Remember me?")]

public bool RememberMe { get; set; }



}

RegisterModel

public class RegisterModel

{



[Required]

[Display(Name = "User name")]

public string UserName { get; set; }



[Required]

[DataType(DataType.EmailAddress)]

[Display(Name = "Email address")]

public string Email { get; set; }



[Required]

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", 

MinimumLength = 6)]

[DataType(DataType.Password)]

[Display(Name = "Password")]

public string Password { get; set; }



[DataType(DataType.Password)]

[Display(Name = "Confirm password")]

[Compare("Password", ErrorMessage = "The password and confirmation password 

do not match.")]

public string ConfirmPassword { get; set; }



}

ChangePasswordModel

public class ChangePasswordModel

{



[Required]

[DataType(DataType.Password)]

[Display(Name = "Current password")]

public string OldPassword { get; set; }



[Required]

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", 

MinimumLength = 6)]

[DataType(DataType.Password)]

[Display(Name = "New password")]

public string NewPassword { get; set; }



[DataType(DataType.Password)]

[Display(Name = "Confirm new password")]

[Compare("NewPassword", ErrorMessage = "The new password and confirmation password 

do not match.")]

public string ConfirmPassword { get; set; }



}

添加数据库模型

解决方案管理器中,右键点击 Models 文件夹,选择添加

以添加MovieDB.cs 为例

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Entity;



namespace MvcDemo.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 : DbContext

{

public DbSet<MovieDB> Movies { get; set; } 

}

}

添加数据库控制器

  1. 在解决方案资源管理器中,右键点击 Controllers 文件夹,然后选择添加、控制器。
  2. 把控制器名称设置为 MoviesController
  3. 选择模板:Controller with read/write actions and views, using Entity Framework
  4. 选择模型类:MovieDB (MvcDemo.Models)
  5. 选择 data context 类:MovieDBContext (MvcDemo.Models)
  6. 选择视图 Razor (CSHTML)
  7. 点击添加

Visual Studio 将创建如下文件:

  • Controllers 文件夹中的 MoviesController.cs 文件
  • Views 文件夹中的 Movies 文件夹

添加数据库视图

以下文件会被自动地在 Movies 文件夹中创建:

  • Create.cshtml
  • Delete.cshtml
  • Details.cshtml
  • Edit.cshtml
  • Index.cshtml

你可能感兴趣的:(asp.net)