Passing Data from Controller to View

In Brief : In this article i am going to explain how the data can be passed from the controller to view. In the previous article you can see how the routing is done in mvc let us proceed  from that article .

In detail : 
Let us consider we want to display the List of programming  Languages as a output, 
We need to pass this data in the form of List from controller action method to View.
public string Index()
            return "Hello world from MVC";

This index method is need to be changed to pass the data to view. 
As we discussed in the article Getting started introduction View is responsible for format the data and present it to the user.

Add new View,  to do this right click inside the index method->select Add View.

Add new View in MVC4

In the Add view dialogue we can see the View name is same as the Controller action method. 
Select the View engine as Razor and Add. This adds the new view with name "Index.cshtml". 
Now look at the Solution explorer, in side the View new folder has been created
 with the name "Home",inside 
this folder "Index" view is saved. 

Solution Explorer with View folder

Here the folder name Home is same as the controller name. All the views belonging to the Home controller resides in this particular folder.

Now we need to pass the data to View,for this let us use the object called ViewBag as follows. 

 public ViewResult Index()
         ViewBag.ProLang=new List()
           return View();

Here "ProgLang" is the Dynamic attribute of the ViewBag
to return the view from controller need to change the return type as ViewResult.
However we can pass the data by making use of the object called "ViewData".Which follows the bellow syntax,
By using this key, value stored in the ViewData can be accessed.

To display the data in View we need to iterate the data passed from the Controller method which is stored in the ViewBag, as follows.


    ViewBag.Title = "Programming Language";

Programming Language

    @foreach (string @strLang in ViewBag.ProLang) {
  • @strLang
  • }

In the above code ‘@‘ symbol is used to switch to the C# code from the html. Wherever the @ symbol is used in the .cshtml file indicates that the following code is C#.
On run we can see the following output,

Data passed from Controller to View-OutPut

Final Touch : In MVC data can be passed from controller to View by using the object like ViewBag,ViewData.Whatever the data received is displayed in the structured format by View. In side the View(.cshtml) '@' symbol is used to turn ON C# coding.
Keep visiting to stepping forward in mvc learning with this Getting Started series.

1 comment: