Passing Data from Controller Action Method to View in ASP.NET Core

We can pass the Data from Controller to View in 2 ways.

1. ViewData

Example for Single value data

Action Controller Code

ViewData[“MyViewName”] =” Type string to pass here”;

To show it in the View, we can write @ViewData[“Key”]

View Code


@ViewData[“MyViewName”]

Controller Action Code

List list=new List();
For(int i=0; i<10;i++)
{
list.Add(i);
}
ViewData[“ListItems”]=list;

Then, in View we need to set the value of ViewData[“ListItems”] as the collection of integer list.

View Code

@foreach (int I in (List)ViewData[“ListItems”])
{
@i <br/>
}

2. ViewBag

 ViewBag is easier and simple way. It accepts data as objects so we can set any type of data.

Controller Code

ViewBag.MyViewBagName=”Send the data that you wanted ”;

View Code

@ViewBag. MyViewBagName

Another example to set the list of integers in ViewBag

Control Code

List list=new List();
For(int i=0; i<10;i++)
{
List.Add(i);
}
ViewBag.ListItems=list;

View Code

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s