ASP.NET MVC - Model

To learn ASP.NET MVC, we will build an Internet application.

Part 7:Add data model.

MVC Model

MVC Modelincluding all application logic (business logic, validation logic, data access logic), except for pure view and controller logic.

With MVC, models can save and operate application data.

Models folder

Models folderincluding classes representing application models.

Visual Web Developer automatically creates a AccountModels.cs file, which includes models for application security.

AccountModels including LogOnModel,ChangePasswordModel and RegisterModel.

Add database model

The database models required for this tutorial can be created through the following simple steps:

inSolution Explorerin the right-click Models folder, selectAdd,class.

for the class MovieDB.cs name it, then clickAdd.

Edit this class:

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; } 
}
}

Note:We have named this table "MovieDBs" (ending with an s). In the previous chapter, we saw the name of the database table "MovieDBs" (ending with an s) used for the data model. Don't you feel a bit strange? However, this is the naming convention to ensure that the controller is linked to the database table.

Add Database Controller

The database controller required for this tutorial can be created through the following simple steps:

  1. Rebuild your project: select Test, and then choose Build MvcDemo from the menu.
  2. In the Solution Explorer, right-click the Controllers folder, and then select Add, Controller.
  3. Set the controller name to MoviesController
  4. Select template: Controller with read/write actions and views, using Entity Framework
  5. Select model class: MovieDB (MvcDemo.Models)
  6. Select data context class: MovieDBContext (MvcDemo.Models)
  7. Select View Razor (CSHTML)
  8. Click to Add

Visual Web Developer will create the following files:

  • MoviesController.cs file in the Controllers folder
  • Movies folder in the Views folder

Add Database View

The following files will be automatically created in the Movies folder:

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

Congratulations to you

Congratulations. You have added the first MVC data type to the application.

Now, you can click on the 'Movie' tab.