ASP.NET MVC - Model
To learn ASP.NET MVC, we will build an Internet application.
Part 7: Adding a data model.
MVC Model
MVC ModelContains all other application logic except pure view and controller logic (business logic, validation logic, data access logic).
With MVC, the model can control and manipulate application data.
Models folder
Models folderContains classes that represent the application model.
Visual Web Developer automatically creates aAccountModels.csfile, which contains the model for application security.
AccountModelsContainsLogOnModel、ChangePasswordModelandRegisterModel。
Add database model
The database model required for this tutorial can be created in a few simple steps:
- InSolution Explorerwindow, right-click Modelsfolder, and selectAddandClass。
- Name the classMovieDB.cs, then clickAdd。
- Edit this class:
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; }
}
}
Note:
We deliberately named the model "MovieDB". In the previous chapter, you saw "MovieDBs" (ending in s) for the database table. This looks a bit strange, but this naming convention ensures that the model connects to the database table, and you must use it this way.
Add database controller
The database controller required for this tutorial can be created in a few simple steps:
- Rebuild your project: selectDebug, then from the menu select Build MvcDemo。
- In Solution Explorer, right-clickControllersfolder, selectAddandController。
- Set the controller name toMoviesController。
- Select template:Controller with read/write actions and views, using Entity Framework
- Select model class:MovieDB (MvcDemo.Models)
- Select data context class:MovieDBContext (MvcDemo.Models)
- Select viewRazor (CSHTML)
- ClickAdd
Visual Web Developer will create the following files:
- Controllersin the folderMoviesController.csfile
- Viewsin the folderMoviesfolder
Add database view
In the Movies folder, the following files are automatically created:
- Create.cshtml
- Delete.cshtml
- Details.cshtml
- Edit.cshtml
- Index.cshtml
Congratulations
Congratulations. You have added your first MVC data model to the application.
Now you can click the "Movies" tab.
Other extensions