Tuesday, 22 March 2022

view data vs ViewBag vs strongly typed binding

 # view data vs ViewBag vs strongly typed binding

## ViewData

1. ViewData is a dictionary of weakly typed objects.
2. To store and retrieve data from the ViewData dictionary we use string keys.
3. String data can be accessed from ViewData dictionary without the need to cast the data to string type.
4. If we are accessing any other type of data, we need to explicitly cast it to the type we are expecting.
5. ViewData is dynamically resolved at runtime, so it does not provide compile-time type checking and as a result we do not get intellisense.
6. Since we do not have intellisense, the speed at which we write code is reduced and the chances of mis-spelling and making typographical errors are also high.
7. We will only come to know about these errors at run time.
8. For this reason we usually do not use ViewData.

## ViewBag

1. With ViewBag we use dynamic properties instead of string keys.
    - in controller, ViewBag.Employee = model;
    - using ViewBag in view, @ViewBag.Employee.Name
2. Even ViewBag creates loosely typed view
3. Both ViewData and ViewBag does not provide compile-time type checking and as a result we do not get intellisense
4. We will only come to know about these errors at run time.

## Strongly typed view

1. Controller Code
     public ViewResult Details()
    {
        Employee model = _employeeRepository.GetEmployee(1);
        ViewBag.PageTitle = "Employee Details";
        return View(model);
    }
2. In View
     @model EmployeeManagement.Models.Employee
   <h3>@ViewBag.PageTitle</h3>
3. Unlike ViewData and ViewBag, a strongly typed view provides compile-time type checking and intellisense.
4. With intellisense support we can be more productive and the chances of mis-spelling and making typographical errors are almost nill.
5. If we do make any errors we will come to know about them at compile time rather than at runtime. So always use a strongly typed view to pass data from a controller to a view.

## ViewModel

1. In some cases, a model object may not contain all the data a view needs. This is when we create a ViewModel. It contains all the data a view needs.
2. eg  
namespace EmployeeManagement.ViewModels
{
    public class HomeDetailsViewModel
    {
        public Employee Employee { get; set; }
        public string PageTitle { get; set; }
    }
}
3. Please note, @model directive has a lowercase "m" and @Model property has a capital letter "M"


No comments:

Post a Comment

Search This Blog

Creating your first "Alexa" Skill

Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...