Wednesday, 29 July 2015

Types of ASP.NET MVC Views

I have found that many entry level developers get confused by the various kinds of Views in ASP.NET MVC Applications. In this post I am trying to clarify these different types of Views.
The type of ASP.NET MVC View depends on the way the data is passed to it from the Controller. There are three ways data can be passed to Views from a Controller. They are as follows:

Using ViewBag or ViewData
  1. Using object of the model which is strongly typed
  2. Using any dynamic type value
On the basis of data transfer mechanism ASP.NET MVC views are categorized as two types:

  1. Dynamic view
  2. Strongly typed view
ViewBag allows you to share data dynamically from Controller to View. You can pass data from Controller to View using ViewBag as follows:


public ActionResult Index()
        {
            ViewBag.ApplicationTitle="Book App";
            ViewBag.Genere = from r in GetAuthors()
                             select r.Genere;
            return View();
        }


ViewBag is a dynamic object and properties get added to it at run time. There is no predefined property for ViewBag. In a View, the ViewBag property can be accessed using the same property name. You can use ViewBag in a View as follows:

@{
    ViewBag.Title = ViewBag.ApplicationTitle;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ViewBag.ApplicationTitle</h2>



While using ViewBag in a View, you may notice that intellisense is not working. This is because the data gets passed dynamically from Controller to View.

When you use ViewBag to pass data, the View is known as a dynamic view.

The second way to pass data from a Controller to a View is using a dynamic type. We are passing a List of Authors as a dynamic type from the Controller to a View as shown below:

public ActionResult Index()
        {
           ViewBag.ApplicationTitle = "Book App";
           var result = from r in GetAuthors()
                             select r.Genere;
            return View(result);
        }


Next create a View for the Index action. To create the View, right click on the action and from the context menu select Add View Option. In Add View dialog box make sure you select the Empty template without model option.
dynamicview



On View you can access a dynamic object passed from the Controller using the dynamic keyword as shown in the image below. Views created using dynamic type data are known as dynamic views.
dynamictype
Intellisense does not help in dynamic views. You can access various properties of dynamic data using dot operator as shown below without help of Intellisense.




No comments:

Post a Comment