Passing data from action method to view

Manideepgoud
Posted by Manideepgoud under ASP.NET MVC category on | Points: 40 | Views : 363
Passing data from action method to view
We can pass the data from action method to view in two ways apart from using return keyword
1.ViewData
2.ViewBag

ViewData
Action method
ViewData["MyViewData"]="This is string";


View code
To get it in view code we use @ViewData["Key"]
@ViewData["MyViewData"]


----Another case ----
Action method
List list=new List();
for(int i=0;i<=5;i++)
{
list.Add(i);
}
ViewData["MyList"]=list;


ViewCode
@foreach(int i in (List)ViewData["MyList"])
{
@i<br/>
}


ViewBag

Action method
ViewBag["MyViewBag"]="This is from viewbag";


View code
@ViewBag.MyViewBag

------------------------Another case----------------------
Action method
List list=new List();
for(int i=0;i<=5;i++)
{
list.Add(i);
}
ViewBag.Listint=list;


ViewCode

@foreach(int in ViewBag.Listint)
{
@i<br/>
}

Comments or Responses

Login to post response