In the last articles we looked at the roles and responsibilities of Controller and Routing in MVC application.View is another component which is an important part of any MVC application.It is one of the pillars of Model View Controller framework.
Views in MVC have a very specific responsibility, to generate the result ,which is mostly HTML, for the request.Most of the times action methods return views though they can return other types as well ,such as Json and File.
Though View generates the result for the user but View can be directly accessed only by the controller.Controller gives the view model data and any other information which needs to be returned to the user.
View is a template which just defines the layout of the HTML which will be rendered.As the view needs to generate the HTML from the model provided to it by the controller ,view contains server side code also apart from the HTML markup.The code which is in the view is specific to the view engine.Webforms view engine has a different code syntax then the razor view engine.As the razor view engine has more fluent syntax so we will consider razor views only.We will create a view and look into the important features of the view.
We add a new Details action method in the Home controller.
public ActionResult Details(int id) { return View(); }
The above code just adds an action method to the controller.The statement return View() is a helper method which returns an object of type ViewResult. ViewResult is a type which helps the ViewEngine render the View.The View() method will render a view with the same name as the action name.So in this case it will search for the Details view.As no Details view exists currently so we have to add the Details view.To add the view right click anywhere inside the Details action method.Following options will be displayed on right clicking inside the method.
We need to select the Add View option to add a new view.On selecting Add view we get the dialog to select view options
We will keep the default settings for now and click the Add button.This will create a view with the name Details.cshtml in the Views/Home folder.
The view was created in the folder Views/Home because the framework expects the view for an action method inside a folder which has the name of the Controller,in this case as the controller name is Home so the View is located inside a folder with the name controller.The file extension is .cshtml which is the file extension for razor views.
Following is the content of the Details.cshtml view.
@{ ViewBag.Title = "Details"; } <h2>Details</h2>
Though the default view does not contain much but we can understand two important points about a view from the above code
- View is just a template which contains code and markup.
- View has access to few objects and properties which we can use to set or get the information in the view. ViewBag is one such object.
Let us now see the significance of the above points to a view.
View as a template
One of the main things to remember while working with views is that the purpose of the view is to generate the HTML which will be returned to the client.Though view may contain the code to format and display the information provided to it by the client but the client works with HTML and is not aware of the actual view contents.View is not even accessible directly by the client ,unlike the webforms which can be directly accessed by the client.
Though client is not aware of the code and other view contents ,understanding what is contained in a view is important if we want to have control over the HTML that is generated by the view.
A view can contain the following elements
- Code in the form of code expressions or code blocks.
- HTML markup
Code expressions are used for writing the response to the output.Below is an example of code expression
@ViewBag.Message
The above expression causes the value contained in the ViewBag.Message property to be written to the response.ViewBag is a property of a dynamic type which is accessible in both the view and the controller.
@ is the character which specifies to the view engine that the following text is code and not markup.We can easily mix the code expressions and the markup as:-
<span> Hello @ViewBag.Message </span>
Code blocks are used to include c#(or vb) statements in a view.Code blocks are declared using curly braces {}.
@{ var message = "Hello razor!"; }
One of the advantages of using razor views is the fluent syntax it provides.We can very easily transition from code to mark and vice versa.
Passing data from Controller to View
ViewBag is just one of the few ways we can use to pass the data from the controller to the view.Other ways we can pass the data from the controller to the view is using the ViewData and the Model.As all of these objects are accessible from both the controller and the view ,so we can pass the information from the controller to the view using these.
For understanding this better,below is an action method from which we are passing the same data using the ViewData ,Model and ViewBag.
public ActionResult Details() { ViewBag.Message = "Hello razor view!"; ViewData["Message"] = "Hellow razor view"; ViewInformation info = new ViewInformation { Message = "Hellow razor view" }; return View(info); }
We can access the different values in the view as
@ViewBag.Message <br/> @ViewData["Message"] <br /> @(((ViewInformation)Model).Message)
The above view just displays the text “Hello razor view!”, three times from the different objects.Though we can use the different objects to pass the data from the controller to the view each should be used depending upon the scenario
ViewBag is a dynamic type so it doesn’t require a cast ,as we can see in the above example.The type of the ViewBag property is determined at runtime.
ViewData is a collection of objects so it can be used to pass multiple objects ,but requires type cast while retrieving the values.
Model is used to a pass a model object which represents an entity for which the view is defined.We can pass specific information to the view which is defined by the model class.We can create strongly type view to avoid casting the model objects in the view.
Lets see how we can create a strongly typed view.
We use Model object to pass the information from the controller to the view when
- We have a set of related information ,for instance we have an entity with different properties.
- We want to aggregate data from different sources such as different database table and want to display the aggregated data to the end user.
If we try to access the Model object from the View we face following challenges
- The View does not provide intellisense
- We need to type convert the Model associated to the View.
The above points are addressed in a strongly typed view.
There is no intellisense support for normal view
Strongly typed view provides intellisense
To create a strongly typed view we just need to add the following statement at the top of the view file.
@model ClassName
For example if we want to create a strongly typed view for a model class called ViewInformation then we can use the following statement
@model ViewInformation
We can pass the model object from the action method as before but now the view is aware of the type it is working with and type mismatches are caught at compile time instead of runtime.
Some of the other important things to be remembered while working with views are:-
- Normal views implicitly inherit from the WebViewPage class ,while strongly typed views inherit from the WebViewPage<T> class ,which is a strongly typed version of the same class.
- While using strongly typed view we can access the Model object as an action method parameter instead passing many different parameters for the different form elements.For example if our strongly typed view is typed for the ViewInformation class then when we submit the view we can access the entire object as an action method parameter as below
public ActionResult Update(ViewInformation viewInformation) {
- We can use layout views to define the basic layout of all the views in our application and to make the layout consistent across the application.The default layout view is called _Layout and is located in the Views/Shared folder.
- Partial Views are used as a part of another view.They define pieces of HTML which becomes part of the parent view.This makes it easy to define an HTML template and use it in multiple views in the application.This avoids duplication.
Leave a Reply