From the course: Learning ASP.NET Core MVC

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Pass data from the controller to the view

Pass data from the controller to the view

From the course: Learning ASP.NET Core MVC

Start my 1-month free trial

Pass data from the controller to the view

- [Voiceover] Now that I've shown you the basics of working with Razor Views, let's see how controllers can pass data to the view so that the view can display that data to the user. For example, let's say we want to be able to set the title, author, date of the post, and the body of the post as variables in the post action of the blog controller, and pass that info to be rendered in the view. The easiest way to do this is with the ViewBag property. This property is a dynamic object that is accessible both on the controller and the view. So, whenever we set a value on this object in the controller, it will also be available in the view. And since it's dynamic, we can just access it as though the property already exists, like this. Then, we can create the view for this action, and just read those properties from the ViewBag to render them right in the page in the appropriate places. Now, when we run the site and access the blog post, we can see the data we've set in the controller…

Contents