Passing Data from Controller to View with ViewModel – Session 21

DataModel - Session 21

In this session of ASP.NET Core Tutorial we will talk about ViewModel and passing data from Controller to View with object of ViewModel. During Session 20 we described Strongly Typed View and passed the data to View through object of the Model. But, we pass some part of data which were not included in Model with ViewBag or ViewData. In this session we will show you the way that you can pass all the data to View with ViewModel and you don’t need to pass any data with Viewbag or ViewData.

What is ViewModel?

ViewModel is a Class which its properties are based on a specific View requirements. Via ViewModel, we can pass all the View required data with an object of that ViewModel. These changes help us to avoid passing any data to View through ViewBag or ViewData.

Creating ViewModel and Passing Data to View with it

First, It is better to create a folder on the Root of your Project with name of ViewModels. Then, create a Class within that folder and set a meaningful name for that. Also, create required properties based on your view needs.

Next, make an object of created ViewModel inside your respective ActionMethod and store required data inside the object. Afterward, pass the Model Object to View with View() method.

Finally, set View @model directive to the created ViewModel and restore the data from the Model.

If you need more details, watch this session video. Also, for being updated about our coming sessions, follow us on Instagram, Facebook, Telegram or YouTube and you can have access to list of all sessions HERE.

You can download this Session Slides form HERE

0.00 avg. rating (0% score) - 0 votes


0 0 votes
Article Rating

Inline Feedbacks
View all comments