Latest web development tutorials

ASP.NET MVC model

In order to learn ASP.NET MVC, we will build an Internet application.

Part 7: Adding data model.


MVC model

MVC model contains in addition to the pure view and controller logic all other application logic (business logic, validation logic, data access logic).

By MVC, the model can control and manipulate the application data.


Models folder

Models folder contains the class represents the application of the model.

Visual Web Developer automatically creates a AccountModels.cs file that contains the model for application security.

AccountModels contains LogOnModel, ChangePasswordModel and RegisterModel.


Adding database model

Database model needed for this tutorial can be obtained by following a few simple steps to create:

  • In the Solution Explorer window, right-click the Models folder and select Add and Class.
  • Name the class MovieDB.cs, and then click Add.
  • Edit this category:
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; }
}
}

Comment:

We deliberately model named "MovieDB". In the last chapter, you've seen for the database table "MovieDBs" (ending in s). It looks strange, but this naming convention ensures model connected to the database table, so you have to use.


Adding database controller

Need for this tutorial database controller through the following a few simple steps to create:

  • Rebuild your project: choose Debug, and then choose Build MvcDemo from the menu.
  • (Solution Explorer) in the Solution Explorer, right-click the Controllers folder, select Add and Controller.
  • Setting controller name MoviesController.
  • Select a template: Controller with read / write actions and views, using Entity Framework
  • Select the model class: MovieDB (MvcDemo.Models)
  • Select the data context class: MovieDBContext (MvcDemo.Models)
  • Select View Razor (CSHTML)
  • Click Add

Visual Web Developer creates the following files:

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

Adding Database Views

In the Movies folder, automatically creates the following files:

  • 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 on the "Movies" tab pages.