Passing Data from Controller To View Edit

Rakesh Kumar Sutar | 17 February 2021 | 65

Introduction

In ASP.Net core MVC 5.0 we need to pass some data from controller to view in some cases. There are various way to pass data from controller to view. We will discuss below.

ViewBag

ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData Dynamic wrapper around the ViewData dictionary. We can also pass data from view to view using ViewBag.

ViewData

ViewBag and ViewData serves the same purpose in allowing developers to pass data from controllers to views. When you put objects in either one, those objects become accessible in the view. We can also Pass Data ViewData to ViewBag and vice versa.

ViewModel

Using ViewModel we can also pass the data from the Controller to View.

TempData

TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only. Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this. You can use TempData to pass error messages or something similar.