Developing Models In ASP.NET MVC

For better understanding of Models, you must know about Entity Framework Code First approach. I’ve already written about Code First.

What are Models in MVC

MVC stands for Model View Controller and Model is the Data access layer in MVC. Essentially, MVC is a design pattern and it is somehow similar to layered based architecture which consists of different layers of software like data access layer, user interface layer, business logic layer and etc. Similarly, in MVC, Models assist in data accessing for the business logic of the application.

Adding a Model to Your Application

Models are basically tables of your database. When you talk about the business logic of the application, it is simply a class. Yes, models at the end of the day are just classes. So when you add a model to the model folder in an MVC application, you’re simply adding a class to it. These classes are objects that work for data transfer between different layers of application and database as well.

Adding Attributes to a Model

When you talk about adding properties to a model, you can assume that you’re setting up the properties of a database table because models at the end of the day act just like classes/tables.

Adding Attributes to Properties

Adding attributes to class properties in models is just like setting up the column properties in database tables. So whenever you hear someone talking about adding attributes to class properties, don’t worry,  it’s a simple thing.

In the example ahead, we will develop a model in ASP.NET Application and analyze it. Let’s get started.

Example:

We will develop a simple example using the following steps:

  • Create a brand new ASP.NET MVC Application ( use built in Template )
  • Add a Model to your Application with name “Student”.
  • Decorate Student model with Attributes.
  • Add a controller and view with CRUD Operation ( built in template will be used )
  • Analyze the database table created against “Student” model.
  • Analyze the User Interface created against “Student” model.

Create a new project in Visual Studio.

Create a new project

Select MVC as template, and click Ok. Your project will be created.

Select MVC as template

Open up solution explorer in order to see your whole project directory. You’ll see all the folders including “models”, “controllers” and “views” folders as well. It’s time to add a new model to your project. Right click on the Models folder and add a new class as given below.

Add new class

Name your class as “Student” and click Add to add a new model.

Student class

After adding the ‘Student’ model, your initial code will look like below.

Student

As you can see it is simply an empty class named Student because models at the end of the day are just classes. Alright now we are going to add some properties to our model.

We’ll add the following properties to the student class.

 

  • ID
  • Name
  • Email
  • Retype Email
  • CNIC
  • City

Update your model class with this code.

Class

We’ve added a few properties to our model class. Do not feel bothered by “RetypeEmail”, it’s not a professional approach but I’ve just used it to keep things simple.

Adding Data Annotation Library to Model

These are just simple properties with no validations or attributes. So it’s time to apply different attributes to our properties. But before that you have to include data annotations library in the model class file.

To do that, look at the picture below.

Namespace

If you closely observe the model, you’ll find properties like ID, which must be auto incremented, Name which must not be empty, and email which must be validated against a regular expression to ensure its legitimacy. To fulfill all these requirements, let’s add data annotations to our project first and later I’ll explain each one of them, one by one.

Update your model class with the following code.

Properties

Let’s discuss each validation one by one,

 

  • [Key]

    Key is used to specify the primary key in a model. Entity framework ‘Auto increments’ your primary key be default.

  • [Display(Name ="Student Name")]

    When you create a property, assign it a name and then add a view for the whole model later, what happens is that as a result of scaffolding, Visual Studio will set the field’s name equal to your property name. So if you want to explicitly change this behavior, you can use the [Display] attribute.

  • [Required(ErrorMessage ="Please write your name…")]

    When you write “Required” with some attribute it becomes compulsory to fill that property with some text. User cannot leave that field empty. You can also specify the error message with this attribute as I’ve done above.

  • [Required,DataType(DataType.EmailAddress)]

    When you have to validate familiar kinds of inputs like email address and etc. You can use built in validations like [EmailAddress]. You can apply two validators on a single property by using a comma to separate them.

  • [Compare("Email")]

    To compare two properties you can use [Compare(“property name to compare to”)] in your model. We will be comparing “Email” and “RetypeEmail” in our example.

  • [Required,RegularExpression("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$",ErrorMessage ="Incorrect CNIC")]

    When it comes to comparing input values to custom patterns, we use regular expressions. For example, if someone is trying to validate the national identity card number in a project and that validation is not available in the default options, then we’ll have to use a customized regular expression. Just place your regular expression inside the regular expression parameter as string it will work fine.

  • [StringLength(30,MinimumLength =12)]

    While working with strings, you have to manage the length of strings in projects. So you can set the maximum and minimum length constraint for the strings inside the model class using the above data annotation.
  • [Range(18,35)]

    While working with integers you can set the maximum and minimum range for any integer property of a model.

Adding Controllers and Views in Project

Now we’ll add a controller and a view for the above student model.

Open up the solution explorer, and right click on the controller folder and follow the sequence as shown in the picture below.

Add controller

When you click to add a controller, another window will be displayed where you can specify the type of controller that you want to add into your project.

There are different types of controllers as being shown. As we’re not discussing controllers in this article, we won’t be discussing them. Simply select the 3rd one as shown in the picture and click Add. When you click on controller's folder to add a scaffolding item to your project, you get the following options

MVC5

Once you click Add, another small window will be displayed where you’ve to specify further information about your controller. There are few things that you must know in order to understand the choices offered to you in this window.

 

  1. Model Class: This is the model class (in our case it is “Student”) upon which you want to build your model.

  2. Data Context Class: This is your database class. If you are not already familiar with entity framework code first approach, read all about it here, Entity Framework Code First From Scratch.

  3. Use Layout page: (if you’re using it in your project) If you’re using layout pages in your project mentioned here. Layout pages are just like master pages in web forms.

  4. Controller Name: Specify your controller name here.

Select all the options appropriately and then click Add.

Select all the options

You might receive the following error. No worries, simply build your project before adding a new item to it.

Error

Press [Ctrl + Shift + B] to build your project and repeat the adding controller procedure again. Once Visual Studio starts adding controller and views to your project, a small window with the name of “Scaffolding” will be displayed.

Scaffolding process

Scaffolding

Scaffolding is a process of creating code. Scaffolding creates code that is based on your model. Scaffolding is built in with cross ASP.NET, which means it can support web forms and web APIs as well. Scaffolding is a onetime thing (once the code is created, it’s yours now to maintain).

Once scaffolding is done, your project will be like the following picture, you’ll notice that controllers and views have been added to your project.

Scaffolding

Expand the student folder inside the views folder and select the view “Create”. You can see that visual studio has created all code regarding to Model for you. Now press F5 to run project.

You can observe the routing of web application from the address bar. We are calling Create method inside the Student Controller. When you click on the Create button to add a new student without properly filling any input field, you will see the error messages clearly.

Enter details

 

Read more articles on ASP.NET:


Similar Articles