Using Model to pass data to View in ASP.NET MVC

By | June 18, 2014

Exploring multiple ways to pass data from Controller to View in an ASP.NET MVC application, so far we have covered following different approaches:

Now in this ASP.NET MVC Tutorial, we are going to implement another approach i.e. using Model for passing data from ASP.NET MVC Controller to View. As we already know that in MVC (Model, View, Controller) pattern, Model represents our domain model corresponding to tables in database. So, we can use this model class to serve the purpose.ViewDataVsViewBagVsTempDataVsModel

::::: Practical Guide to ASP.NET Web API :::::

Consider the following Model class we have already used in our previous implementations:

Now, we are done with our Model class (i.e. Employee). For the purpose of this implementation, we are loading data directly to our Model in EmployeeController. In a real implementation, we must be fetching this data from a data source e.g. a database. So, the Controller has following code:

In above code example, you can see that as opposite to ViewData and ViewBag approach in other ASP.NET MVC Tutorial, we are passing data (i.e. employees) as parameter to View instead of placing in another store and calling as View().
Finally, updating our View to get and display data passed from Controller as:

At the top of our View (i.e. Index.cshtml), we have referred to our Model class (i.e. Employee) using IEnumerable. Further in View, we are using foreach to access and display data as needed. When we run this application, our View will display the Model data from Controller as follows:

Model in ASP.NET MVC

Using Model to pass data to View in ASP.NET is pretty simple as well as more appropriate because we are fetching data from permanent store and loading in our Model classes in most of the cases. Also, we use it to perform all CRUD (Create, Retrieve, Update, Delete) operations. Hopefully, this ASP.NET MVC Tutorial will help in understanding the mentioned approach in a more effective way.
Previous: ViewBag and ViewData in ASP.NET MVC

Other ASP.NET MVC5 Tutorial and more related articles:

Top 10 Interview Questions and Answers Series: