Model in ASP.Net MVC : Part 1

What is 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: 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 actually retrieve information from a database table. In Part 2 (that I will write soon) of this article we will see how to do this using Entity Framework in ASP.NET MVC.

Step 1: 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 and "View Engine as razor" as shown below:


Click "OK".

Step 3: 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: Let's add some auto-implemented properties to the Student class. After adding properties your class will look like:


Step 5: Add a Controller to your project and name it "StudentController" as shown below


Click on the "Add" Button.

Step 6: 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 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:


Step 7: 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: Write the following code in the Index.cshtml to display data in tabular format.


Step 9: 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, you will get expected output.

The next article we will see how to access data using the Entity Framework.

Similar Articles