In This article I am going to explain views in mvc application.I want to display list of countries as shown in figure.
Now go to visual studio create one empty mvc
cotroller or we can use home controller and look at the index action method
return type is ActionResult but we want to display the list of countries means
we have to return the list of strings.
public List<string>
Index()
{
return
new List<string>()
{
"India",
"France",
"USA",
"Canada",
"England"
};
}
Run the application, give the controller name in url
and we expect the output as list of countries but we will get name of the type
(System.Collections.Generic.List`1[System.String])
To fix this we can actually add a view .The purpose of
view is to format the data in page we want and present it to the end user.
First we need to add a view to the project, right click any where on the index
function and select add view.
The name of view and the name of the controller action
method matching here, select razor as view engine and leave the rest of defaults
we discuss strongly typed view in coming articles. Before going to click on add
just watch the views folder ,it has no files now add a view watch the views
folder it has index.cshtml file.
To return a view first we have to change return type of
index action method. I will change return type as ActionResult, view inherits
from ActionResult. We have to pass the list of counties from controller to
view,to achieve this we need to store these list of counties in ViewBag or
ViewData. ViewBag and ViewData is a mechanism to pass data from
controller to view.
Here Counties (viewbag.countries) is dynamic property,
you can give any meaningful name instead of countries.
Now go to view i.e Index.cshtml ,In this view we need
to retrieve the list of countries from the viewbag object and display them to
the user. Let’s change the code in the Index.cshtml
In above code we use @ symbol to switch between html and c# code. Now run the
application and see the following output
tags:views in mvc ,views in asp.net mvc ,views in mvc 4,
views in mvc 4
views in mvc 4