What is a Model?
The MVC Model contains all application logic (business logic, validation logic, and data access logic), except pure view and controller logic. With MVC, models both hold and manipulate application data.
Part 1. Demonstrating model class usage in MVC
Let's do one simple demo of how to use the Model class in MVC. In this demo, we will hard-code our data in a Controller and finally, we will retrieve data from the Controller using the Model class. But in reality, we retrieve information from a database table. In Part 2 (which I will write soon) of this article we will see how to do this using Entity Framework in ASP.NET MVC.
Step-by-step guide
Step 1. Setting up the Visual Studio project
Start Visual Studio then select "File" -> "New" -> "Project..." then select "MVC 4 Web Application" and name it "MvcModelDemo".
Step 2. Select "Empty" from the project templates
Select "Empty" from the Project templates and "View Engine as a razor" as shown below.
Click "OK".
Step 3. Creating the model Class "Student"
In the Solution Explorer, right-click on the Model folder class and name it "Student.cs" as shown below.
Click on the "Add" Button.
Step 4. Adding properties to the student class
Let's add some auto-implemented properties to the Student class. After adding properties your class will look like this.
Step 5. Adding the StudentController
Add a Controller to your project and name it "StudentController" as shown below.
Click on the "Add" Button.
Step 6. Using Namespaces in the controller
Now since our Student Model class is in the "MVCModelDemo.Model" namespace, we need to use the "MVCModelDemo.Models" namespace in the Student Controller class. Here we will hard-code some data to the properties present in the Student class. But notice that in reality, we may use a database table column to assign a value to these properties. After doing the stuff described above your controller class will look like this.
Step 7. Adding a strongly typed view
Let's add a view to our project. To add a view, right-click in the index method and click on "Add view". This time we will select our view as strongly typed because we want to map a view with the Student model class. In the Model class, a drop-down list will select a Student Model class as shown below.
Click on the "Add" Button.
Note. If your Model class drop-down list is empty then build your project.
Step 8. Writing code to display data
Write the following code in the Index.cshtml to display data in tabular format.
Step 9. Running the project and handling errors
Press F5 to run your project. You will get the following output.
Note. If you're getting the following error.
Don't worry. Go to the RouteConfig.cs file under the App_Start folder and change the controller name "Home" to "Student" as shown below.
Now run your project, and you will get the expected output.
In the next article, we will see how to access data using the Entity Framework.