| Dua Ali
In MVC, M stands for Model which is like a normal C# class. Model is responsible for handling database related changes and also responsible for handling data and business logic. The shape of data is represented by models.
As seen in the diagram above, when a user types a URL into their browser, the request is sent to the server, where it is routed to the proper controller. Execute the relevant controller action method based on the request controller. If the model has a database operation, it will forward the request to it. The database-related activity will then be performed, and the request will be sent back to the controller. The controller returns the response to the user after finishing this request.
To demonstrate, how actually models work, here is an example implemented on Visual Studio for better understanding.
Step 1: Create an MVC project on Visual Studio named “modelDemo”
Step 2: Right click on Models folder and then add a simple class and name “Book.cs”
Step 3: After naming class for model, click on Add button at the bottom.
Step 4: Now we will populate our Model that is books.cs
- Here ‘Books’ is functioning just like an entity of a database.
- BookId, BookName, Author, Genre are the fields on this entity each of which holds a record.
- GetAllBooks() is a method that is taking some records for the entities and would return the same as a response in the form of a list.
Step 5: We need to add the following code in the HomeController to call the method containing the list in the Model class.
- Using modelDemo.Models should be imported in order to access our model.
- The code which calls the method resides in model class and returns to the view.
Step 6: As soon as the project is created, we have some default files in the View folder. Here we will use Index.cshtml to make our view for the list.
We will open Index.cshtml and add the following code.
- Use the @model IEnumerable<modelDemo.Models.Books> on the top of the View file to import the list from the Model.
- Add the above HTML code in order to show output in the form of table. Foreach loop is used to retrieve records from each row (that can be multiple rows).
After completing all the above mentioned steps, we will run our project to see our final output of the project.
So this is how we have used a Model to display our data in MVC.
Join us next time, as we continue our journey of learning canvas apps.Click here to learn more about Imperium's Power Apps Services. We hope this information was useful, and we look forward to sharing more insights into the Power Platform world.