Adding a Model in ASP.NET MVC 5 Project Step by Step

In this chapter, you will learn:1. How to Add a Model class in ASP.NET MVC 5 Project2. How to Access Model Data in View using Controller3. Complete Programming Example

This chapter is going to be very important for you. If you study this chapter deeply, then you will be able to understand all the mechanism of Model just in one chapter. So, I recommend you to study carefully this chapter with full concentration.

Adding a Model

I have opened my existing project CompShop for adding a model. If you haven't created CompShop application earlier, then don’t worry and create a new MVC 5 Project with your preferred name.

Step 1: Open Solution Explorer and Look for the Models Folder. If Models Folder is not there, then just create a new folder: Models. After that right click on ModelsAddClass…

Let’s take a moment to understand this code
Here, This class will be mapped to database as follows:

Class name ItemList will be your table name in the database.

Each member of this class like ID, Name, Category, and Price will be mapped with Table Column with the same name.

The datatype of this property will be the datatype of the column in the table.

Now, you must be thinking that where is a database and where is connection string? Your answer is in the next chapter. Here, I am using the simple model class without database and entity framework. My motive is to teach you everything but step by step. In the next chapter you will surely learn Database part and Entity Framework but here only focus on how models work.

Step 4: Create a New Controller ItemController.cs. Right click on ControllersAddController…

Step 9: Run the project and navigate to http://localhost:1233/Item/Index

Summary

In this chapter, you learned how to add model and access model data in view pages. In the next chapter, we will discuss more clearly about Models and will show you an example of the database. We will create a database, tables and add some data to it then will access these data using models. So, don’t skip the next chapter How to Access Data using Models from Database asp.net mvc5.