Dynamic vs Strongly Typed Views

There are three ways to pass information from a controller to a view in ASP.NET MVC

  1. As a strongly typed model object
  2. As a dynamic type (using @model dynamic)
  3. Using the ViewBag

Strongly typed views:

Views know about the model class at compile time is called as strongly types views

Below steps explains about creating the strongly typed view using Add View dialog. In this example Employee information (act as model) will be displayed in the view

Step 1:Create simple MVC application and updated the controller class as mention



  


  public class HomeController : Controller
                {
                    public class Employee
                      {
                        public string Name;
                        public int Age;
                      }

                List<Employee> empList = new List<Employee>
                      { 
                        new Employee { Name = "Santosh Kumar Singh", Age=25},
                        new Employee { Name = "Reena kumari", Age=22},
                        new Employee { Name = "Gagan", Age=26 }
                      };


                public ActionResult Organization()
                        {
                        return View(empList);
                        }
               }





Step 2:Compile the project using Ctrl+Shift+B

Step 3:Select the model class, Scaffold template and click ‘Add’ button.





Step 4:



Dynamic typed:-

View does not know what type of object information it is displaying to the user. View knows about the model class only at the runtime

Step 1:- Consider the same example mention above is created to display the employee information in the view without strongly typed



  

   {
                    public class Employee
                      {
                        public string Name;
                        public int Age;
                      }

                List<Employee> empList = new List<Employee>
                      { 
                        new Employee { Name = "Santosh Kumar Singh", Age=25},
                        new Employee { Name = "Reena kumari", Age=22},
                        new Employee { Name = "Gagan", Age=26 }
                      };


                public ActionResult Organization()
                        {
                        return View(empList);
                        }
               
                 public ActionResult DynamicModel()
                        {
                         return View(empList);
                        }
                }
                




Step 2:On View() method in DynamicModel action method, right click and select ‘Add View’



Step 3:In the generated view file, you can see that there is no type mention about the ‘Employee’. It is mentioned as dynamic, so there will not be any intelligence while accessing the model object.



Step 4:Output:-