ASP.NET MVC > Passing data

Pass data from action method to View in ASP.NET MVC

How to pass data from controller action method to the View?


Passing data from action method to the view can be done using two ways (apart from using return keyword).

ViewData

ViewData is a dictionary where we store data against a key. The data can be stored as an object so it can be of any data type or object.

ACTION METHOD CODE

ViewData["MyViewData"] = "This is a string.";

To access it in the View, we can use @ViewData[“Key”]

VIEW CODE

@ViewData["MyViewData"]

Another example

ACTION METHOD CODE

List list = new List(); 
for(int i = 0; i< 5; i++)
{
    list.Add(i);
}

ViewData["MyList"] = list;

Here, we are setting the value of ViewData[“MyList”] as the collection of integer list.

VIEW CODE

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

To retrieve the integer stored in the collection, we need to unbox it the way it is done above and retrieve the data in each iteration.

ViewBag

(Easier and better)

ViewBag is also a dictionary however it is of dynamic dictionary. Where we can set ViewBag.PropertyName (any name as it is of dynamic type) and access it from the View.

ACTION METHOD CODE

ViewBag.MyViewBag = "This data is coming from ViewBag, that can have a dynamic property.";

ViewBag also accepts data as object so we can set any type of data.

VIEW CODE

@ViewBag.MyViewBag

Another example

Action method code

Populate the list of int and set it into ViewBag.

List list = new List(); 
for(int i = 0; i< 5; i++)
{
list.Add(i);
}
ViewBag.ListInt = list;

View Code

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

Notice that to list the integer value from ViewBag we didn't unbox it to the List<int> in the foreach loop and still it works as ViewBag is of dynamic type so razor engine understands it and unbox the ViewBag.ListInt for us and loop through each integer values.

 Views: 26183 | Post Order: 59



Write for us






Hosting Recommendations