Models In MVC Application

Overview

In this article, we will see what models are in MVC Application. Suppose, we want to retrieve a student’s information from the students table. The table given below follows, where we have to display its corresponding Id, Name, Gender and City as.

Id 1
Name Akshay
Gender Male
City Mumbai

We want an output in a tabular format.

To retrieve information, we need to have student model class. Add a class file in Models folder, name it as Students.cs and assign the container properties to it, as given below.



Now, add a controller, name it as StudentController and change the action method from Index to Details as.



We want the details, which should be retrieved from the database. At the moment, we will hard code the values and in the later articles, we will see how to retrieve the details from the database.

Thus, import the models namespace, so that we can use StudentsClass, which is placed inside our models folder as.



As you can see, we had hard coded the values here, as we need to hand over this object to the view and our view will display its various details.

Thus, add a view as Details.

Now, we have to bind the various details like Id, name, city, gender to our model as.



View Code is given below.

  1. @model ModelsInMVCApp.Models.Students  
  2.   
  3. @{  
  4.     ViewBag.Title = "Details";  
  5. }  
  6.   
  7. <h2>Details</h2>  
  8.   
  9. <table style="font-family:Arial">  
  10.     <tr>  
  11.         <td>  
  12.             <b> id:</b>  
  13.         </td>  
  14.         <td>  
  15.             @Model.id  
  16.         </td>  
  17.     </tr>  
  18.     <tr>  
  19.         <td>  
  20.             <b> Name:</b>  
  21.         </td>  
  22.         <td>  
  23.             @Model.name  
  24.         </td>  
  25.     </tr>  
  26.     <tr>  
  27.         <td>  
  28.             <b> Gender:</b>  
  29.         </td>  
  30.         <td>  
  31.             @Model.gender  
  32.         </td>  
  33.     </tr>  
  34.     <tr>  
  35.         <td>  
  36.             <b> city:</b>  
  37.         </td>  
  38.         <td>  
  39.             @Model.city  
  40.         </td>  
  41.     </tr>  
  42.   
  43. </table>  
This is the simple code to display the details. Now, we have to pass our student object to our view as.


Now, save the solution and run the app. We will get the output as-



We had got expected output.

Conclusion

Thus, the controller responds to the URL requests, gets the data from the model and hands it over to the view. The view then renders the data. Model can be entities or business objects.

Thus, this was Models in MVC Application. Hope, this article was helpful!!

 


Similar Articles