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

1. ViewData

Example for Single value data

Action Controller Code

[code language=”csharp”]
ViewData[“MyViewName”] =” Type string to pass here”;
[/code]

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

View Code

[code language=”csharp”]

@ViewData[“MyViewName”]

[/code]

Controller Action Code

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

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

View Code
[code language=”html”]
@foreach (int I in (List)ViewData[“ListItems”])
{
@i <br/>
}
[/code]
2. ViewBag

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

Controller Code

[code language=”csharp”]
ViewBag.MyViewBagName=”Send the data that you wanted ”;
[/code]

View Code
[code language=”html”]
@ViewBag. MyViewBagName
[/code]
Another example to set the list of integers in ViewBag

Control Code

[code language=”csharp”]
List list=new List();
For(int i=0; i<10;i++)
{
List.Add(i);
}
ViewBag.ListItems=list;
[/code]

View Code
[code language=”html” 1=”(int” 2=”I” 3=”in” 4=”ViewBag.ListItem)” 5=”{” 6=”@i” 7=”<br/>” 8=”}” 9=”[/code”][/code]

Leave a Reply

Your email address will not be published. Required fields are marked *